Sub topic 3
Why Files Must Share a Structure
Assume you know Excel tables, CSV and .xlsx files, and the Power Query editor. Power Query can append many files only when their transformed tables have compatible columns and meanings.
Consistent Structure
Each file should use the same column names, data layout, and data types. For example, every monthly CSV should contain Date, Region, and Amount. A file with SalesAmount, a missing Region column, or an extra title row can cause errors or produce null values.
Apply cleanup steps in Transform Sample File. Power Query uses that query as a template for every file. Rename columns, remove header rows, and set types there rather than fixing only the combined result.
flowchart TD
A[Files with the same layout] --> B[Sample-file transformation]
B --> C[Apply function to every file]
C --> D[One combined table]Loading and Refreshing
After checking the preview, choose Home > Close & Load to place the result in an Excel table. When files are added, replaced, or corrected, use Data > Refresh All. Power Query reruns the folder query and its transformation steps.
A refresh does not repair a changed layout. It reruns the same logic, so a new column name or unexpected file can still break the query.
Reading the M Code
Power Query stores steps in M. The formula bar or Advanced Editor shows the code. A typical folder source and filter look like this:
let
Source = Folder.Files("C:\Data\Sales"),
CsvOnly = Table.SelectRows(
Source,
each [Extension] = ".csv"
and not Text.StartsWith([Name], "~$")
)
in
CsvOnlyFolder.Files returns file metadata and binary Content. Table.SelectRows keeps rows that meet a condition. Each following step receives the previous step's table.
Writing a Custom Combine Query
For CSV files, parse each binary value, then combine the resulting tables:
let
Source = Folder.Files("C:\Data\Sales"),
Files = Table.SelectRows(Source, each [Extension] = ".csv"),
Parsed = Table.AddColumn(
Files,
"Data",
each Table.PromoteHeaders(
Csv.Document([Content], [Delimiter = ",", Encoding = 65001])
)
),
Combined = Table.Combine(Parsed[Data])
in
CombinedKeep [Name] before expanding Data if you need file-level provenance.
Making the Folder Path Easy to Change
Create a text parameter such as FolderPath, then replace the literal path with FolderPath. Changing the parameter updates the source without editing M code.
Troubleshooting
- Missing column: check spelling, headers, and whether every file has that column.
- Temporary files included: exclude names beginning with
~$. - Subfolder files included: use
Folder.Filescarefully; it searches subfolders. Filter[Folder Path]when necessary. - Type errors: set types after cleanup and inspect dates, decimal separators, and blank values.
Exercise
A new CSV has the same columns but an extra title row. Where should you remove that row?
Show answer
Remove it in the Transform Sample File query so the step applies to every file.