Sub topic 12
Reading the M code
This chapter assumes you can already connect to a folder, filter the file list, and run Combine & Transform Data. It explains the M code (the Power Query formula language) behind those steps. You will learn to read it, spot where each step came from, and change it safely.
Why read M at all
Every click in the Power Query editor adds a line of M code. Most of the time you never need to look at it. You need it when a step errors, when a setting is not in the interface, or when you want to change many steps at once.
You can see the code in two places:
- Formula bar: shows the code for the selected step. If it is hidden, turn it on under View > Formula Bar.
- Advanced Editor: shows the whole query. Open it with Home > Advanced Editor.
The shape of a query
A query is a let ... in expression. Each line between let and in is a step with a name. A step can use the result of any earlier step. The value after in is what the query returns.
let
Source = Folder.Files("C:\Data\Sales"),
CsvOnly = Table.SelectRows(Source, each [Extension] = ".csv" and not Text.StartsWith([Name], "~$")),
Kept = Table.SelectColumns(CsvOnly, {"Name", "Content"})
in
KeptRead it from the top:
SourcecallsFolder.Files, which returns one row per file in the folder and all its subfolders.CsvOnlykeeps rows where[Extension]is.csvand the name does not start with~$. Excel creates~$files as temporary lock files while a workbook is open.Keptkeeps only theNameandContentcolumns.
The query returns Kept, because Kept follows in.
Steps are names, not order
M does not run lines top to bottom. Each step is evaluated only when something needs its value, which is called lazy evaluation. The order on screen is just the order of dependencies. The step names in the Applied Steps pane are the same names you see in the code. A name with spaces appears as #"Changed Type".
The pieces of the syntax
| Piece | Example | Meaning |
|---|---|---|
| Step reference | `Source` | The result of an earlier step |
| Column reference | `[Name]` | The value in the Name column of the current row |
| `each` | `each [Amount] > 0` | Shorthand for a function with one argument, named `_` |
| List | `{"Name", "Content"}` | Ordered values in braces |
| Record | `[Delimiter = ",", Encoding = 65001]` | Named fields in square brackets |
| Text | `"C:\Data\Sales"` | Text in double quotes. Backslash is not an escape character in M |
M is case sensitive. Table.SelectRows works. table.selectrows does not. Also, [Extension] = ".csv" is a case-sensitive comparison, so a file named REPORT.CSV has the extension .CSV and is dropped. Use Text.Lower([Extension]) = ".csv" if the case varies.
Record versus column reference
Square brackets mean two things. After a function call or a value, [Content] reads a field. Inside a list of options, [Delimiter = ","] builds a record. The context tells you which one it is. Inside each, [Name] means "the Name field of the current row".
Reading the combine step
The Combine & Transform Data command generates helper queries. You can write the same logic by hand in one query. This version parses CSV files directly.
let
Source = Folder.Files("C:\Data\Sales"),
CsvOnly = Table.SelectRows(Source, each [Extension] = ".csv"),
Parsed = Table.AddColumn(CsvOnly, "Data", each Table.PromoteHeaders(Csv.Document([Content], [Delimiter = ",", Encoding = 65001]))),
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
TypedStep by step:
Parsedadds a column namedData. For each row,Csv.Documentturns the binary[Content]into a table.Encoding = 65001means UTF-8.Table.PromoteHeadersthen uses the first row as column names.Keptdrops everything exceptNameandData. TheNamecolumn is what keeps the source file name on every row.Expandedunfolds each nested table into regular columns. You list the columns to take. A column missing from a file produces an error, and an extra column in a file is ignored.Typedsets the data types. It comes last on purpose, so the types apply to the combined table.
Comparing with the generated version
The generated queries split this work into pieces. The sample file query holds the cleanup steps. A function query wraps those steps so they can run once per file. The main query calls that function for every row of the file list.
The hand-written version has fewer moving parts. The generated version has one advantage: you edit the Transform Sample File query in the interface, and the function updates. In a hand-written query, you edit the Parsed step yourself. Choose by how often the logic changes and who maintains the workbook.
Reading an Excel workbook version
For workbooks, Excel.Workbook replaces Csv.Document.
let
Source = Folder.Files("C:\Data\Budgets"),
Workbooks = Table.SelectRows(Source, each [Extension] = ".xlsx" and not Text.StartsWith([Name], "~$")),
Parsed = Table.AddColumn(Workbooks, "Data", each Excel.Workbook([Content], true, true){[Item = "Budget", Kind = "Sheet"]}[Data]),
Combined = Table.Combine(Parsed[Data])
in
CombinedThe Parsed line packs several operations together:
Excel.Workbook([Content], true, true)returns a table listing the workbook's sheets, tables, and named ranges. The firsttrueuses the first row as headers. The secondtrueasks for delayed type detection, which is faster.{[Item = "Budget", Kind = "Sheet"]}is a lookup. Braces after a table select a row by matching the record. It returns an error if no row matches, so a workbook with noBudgetsheet fails the whole query.[Data]takes the table from that row.
Parsed[Data] is a list of tables, one per file. Table.Combine appends them into a single table. Unlike the first example, this one does not keep the file name. To keep it, add Name before combining, as in the next section.
Modifying the code safely
Here is a small edit to the workbook query that keeps the file name.
let
Source = Folder.Files("C:\Data\Budgets"),
Workbooks = Table.SelectRows(Source, each [Extension] = ".xlsx" and not Text.StartsWith([Name], "~$")),
Parsed = Table.AddColumn(Workbooks, "Data", each Table.AddColumn(Excel.Workbook([Content], true, true){[Item = "Budget", Kind = "Sheet"]}[Data], "Source.Name", (row) => [Name])),
Combined = Table.Combine(Parsed[Data])
in
CombinedThis has a bug worth understanding. Inside the inner function, [Name] refers to the inner row, which is a budget row, not the file. The new column is not guaranteed to hold the file name. Use a named variable from the outer row instead:
let
Source = Folder.Files("C:\Data\Budgets"),
Workbooks = Table.SelectRows(Source, each [Extension] = ".xlsx" and not Text.StartsWith([Name], "~$")),
Parsed = Table.AddColumn(Workbooks, "Data", (file) => Table.AddColumn(Excel.Workbook(file[Content], true, true){[Item = "Budget", Kind = "Sheet"]}[Data], "Source.Name", each file[Name])),
Combined = Table.Combine(Parsed[Data])
in
CombinedHere (file) => names the outer row, so file[Name] is always the file name. This is the reason to prefer explicit parameter names over each when functions are nested.
Common reading errors
- Wrong step after
in. If the query returns an earlier step, later steps are ignored. Check the last line. - Missing comma. Every step except the last needs a trailing comma. The editor reports "Token Comma expected".
- Type applied too early. Setting types before combining can fail on one bad file. Do it after the expand.
- Hard-coded column names. The list in
Table.ExpandTableColumnbreaks when a file renames a column.
Exercise
In the query Parsed = Table.AddColumn(CsvOnly, "Data", each Csv.Document([Content])), what does [Content] refer to, and why does the query fail if you swap each for a function that has the parameter named file but you still write [Content]?
Show answer
[Content] is the Content field of the current row of CsvOnly, which holds the file's binary data. With each, the current row is available implicitly. With (file) =>, you must write file[Content], because a bare [Content] has no implicit row to read from and gives an error.
Exercise
A workbook query returns an error for one file only. The code contains {[Item = "Budget", Kind = "Sheet"]}. What is the most likely cause?
Show answer
That file has no sheet named Budget, so the lookup finds no matching row and returns an error. Check the sheet name in that file, or filter such files out beforehand.