Sub topic 13
Writing your own combine query
This chapter assumes you can read basic M, the language behind Power Query. It also assumes you have used Folder.Files and know what the Combine & Transform Data command generates. Here you replace the generated sample file, parameter and function queries with one query that you control.
When to write your own
The generated queries work well when every file is a CSV or when you want the first sheet of each workbook. Write your own query when you need any of the following:
- A specific sheet from each workbook, found by name.
- Skipping files that lack the expected sheet instead of failing the refresh.
- Fewer helper queries in the workbook.
- Logic that is visible in one place instead of spread across four queries.
The cost is that nothing updates the query for you. If the file layout changes, you edit the M yourself.
The shape of every combine query
Every custom combine follows the same four steps.
- List and filter. Folder.Files returns one row per file, including files in subfolders.
- Parse. Add a column whose value for each row is a table built from that row's binary Content.
- Combine. Join the nested tables into one, either by expanding the column or with Table.Combine.
- Type. Set data types last, on the combined table.
Combining CSV files
This query parses each CSV, promotes headers and keeps the file name.
let
Source = Folder.Files("C:\Data\Sales"),
CsvOnly = Table.SelectRows(
Source,
each Text.Lower([Extension]) = ".csv" and not Text.StartsWith([Name], "~$")
),
Parsed = Table.AddColumn(
CsvOnly,
"Data",
each Table.PromoteHeaders(
Csv.Document([Content], [Delimiter = ",", Encoding = 65001]),
[PromoteAllScalars = true]
)
),
Kept = Table.SelectColumns(Parsed, {"Name", "Data"}),
Expanded = Table.ExpandTableColumn(Kept, "Data", {"Date", "Region", "Amount"}),
Typed = Table.TransformColumnTypes(
Expanded,
{{"Date", type date}, {"Region", type text}, {"Amount", type number}}
)
in
TypedSome details in this query matter:
Text.Lower([Extension])makes the filter match.CSVas well as.csv. The comparison=is case-sensitive in M.Encoding = 65001reads the file as UTF-8. Use1252for older Windows exports.- The
~$test removes the lock files Excel creates next to open workbooks. Those files are not valid CSV data. Table.ExpandTableColumnneeds the column names written out. A file with a renamed column produces nulls for it, or an error if a listed column is missing from every file.
Combining one named sheet from many workbooks
Workbooks need Excel.Workbook instead of Csv.Document. It returns a table that lists every sheet, table and named range in the file. You then select the item you want.
let
Source = Folder.Files("C:\Data\Budgets"),
Workbooks = Table.SelectRows(
Source,
each Text.Lower([Extension]) = ".xlsx" and not Text.StartsWith([Name], "~$")
),
Parsed = Table.AddColumn(
Workbooks,
"Data",
each try Excel.Workbook([Content], true, true){[Item = "Budget", Kind = "Sheet"]}[Data] otherwise null
),
Found = Table.SelectRows(Parsed, each [Data] <> null),
Tagged = Table.AddColumn(
Found,
"Tagged",
each let fileName = [Name]
in Table.AddColumn([Data], "Source.Name", each fileName, type text)
),
Combined = Table.Combine(Tagged[Tagged])
in
CombinedThe {[Item = "Budget", Kind = "Sheet"]} part is a record lookup. It returns the one row where Item is Budget and Kind is Sheet, and [Data] takes that row's table. The second and third arguments of Excel.Workbook mean "use the first row as headers" and "delay loading data types", which keeps the query fast.
The try ... otherwise null wrapper turns a missing sheet into null. The next step, Found, then drops that row. Without it, one workbook lacking a Budget sheet fails the whole refresh.
The let fileName = [Name] line copies the file name into a variable first. Inside the inner each, the bare [Name] would refer to a row of the nested table, not to the file row.
How Table.Combine matches columns
Table.Combine matches columns by name, not by position. A column that exists in only some files appears in the result, with null for the files that lack it. Two spellings of the same header, such as Amount and amount, become two separate columns.
Wrapping the parser in a function
If the parsing logic grows, move it into a function query. Create a blank query named fnParseCsv with this body.
(content as binary) as table =>
let
Raw = Csv.Document(content, [Delimiter = ",", Encoding = 65001]),
Promoted = Table.PromoteHeaders(Raw, [PromoteAllScalars = true]),
Typed = Table.TransformColumnTypes(
Promoted,
{{"Date", type date}, {"Region", type text}, {"Amount", type number}}
)
in
TypedIn the main query, call it with each fnParseCsv([Content]). This is the same idea as the generated Transform File function, but you wrote it, so you know exactly what it does. One edit to the function changes every file.
Choosing between expanding and Table.Combine
| Approach | Strength | Weakness |
|---|---|---|
| Table.ExpandTableColumn | Explicit column list, easy to read | Fails or silently drops columns when headers change |
| Table.Combine | Keeps every column from every file | Can create unwanted extra columns, and a column list must be handled separately |
Use Expand when the layout is fixed and you want a loud error if it changes. Use Table.Combine when the layout may vary and you would rather see extra columns than lose data.
Testing a custom query
- Run the query on a folder with two or three files first.
- Check the row count against the sum of the rows in each file.
- Add a file with a missing sheet or a renamed column and confirm the query behaves the way you intended.
- Refresh after you drop in a
~$lock file. Open one workbook in the folder and refresh while it is open.
Common mistakes
- Forgetting that Folder.Files includes subfolders. Add a filter on
[Folder Path]if you only want the top level. - Hard-coding the sheet name when some files use
Budgetwith a trailing space. - Typing columns before promoting headers, which makes the type step fail with a missing-field error.
- Leaving a first step such as
Changed Typeauto-generated with column names that no longer match.
Exercise
Your workbook-combining query fails on refresh because one file has no sheet named Budget. Which change makes the query skip that file, and why is a second step needed after it?
Show answer
Wrap the sheet lookup in try ... otherwise null so the missing sheet yields null instead of an error. Then add a Table.SelectRows step such as each [Data] <> null to drop those rows. Without the filter step, Table.Combine would receive a null where it expects a table and would fail.
Exercise
A combined CSV query returns two columns named Amount and amount after a new file arrives. Which function produced this, and what would you do?
Show answer
Table.Combine matches column names exactly, including case, so the new file's differently cased header became a separate column. Fix it by renaming the column in the parsing step, for example with Table.RenameColumns inside the function that parses each file, so every file has the same names before combining.