Sub topic 14
Reading and editing M code
What this chapter assumes
You have already built queries in the Power Query Editor and can read the Applied Steps pane. You know that each click records a step. This chapter shows the text behind those steps. M is the language Power Query uses, and each step is one line of it. You will learn to read that text and make small, safe edits.
The shape of every query
Every query is one let ... in expression. The let block holds a list of named steps, separated by commas. The in line names the step whose result the query returns.
let
Source = Csv.Document(File.Contents("C:\Data\sales.csv"), [Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.Csv]),
#"Promoted Headers" = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
#"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers", {{"OrderID", Int64.Type}, {"Amount", type number}})
in
#"Changed Type"Each step takes the result of an earlier step as its first argument. Source feeds #"Promoted Headers", which feeds #"Changed Type". The Applied Steps pane is a list view of these lines in order.
The #"..." syntax is a quoted identifier. M needs it for any step name that contains spaces or special characters. A name like Typed needs no quotes.
Where to see and edit the code
- Formula bar. Turn it on under View, then Formula Bar. It shows the M for the selected step only. You can edit that one line in place.
- Advanced Editor. Open it from Home or View. It shows the whole query, so you can add, remove, or reorder steps and see the
letandinlines.
Use the formula bar for a one-line tweak. Use the Advanced Editor when you need to see how steps connect.
Reading a step
Take this line:
Table.TransformColumnTypes(#"Promoted Headers", {{"OrderID", Int64.Type}, {"Amount", type number}})Read it in three parts:
- The function is
Table.TransformColumnTypes. The prefix before the dot is the kind of value it works on. - The first argument is the input table, normally the previous step.
- The remaining arguments configure the action. Here they are a list of column and type pairs.
M has three bracket styles that you will see everywhere:
| Syntax | Meaning | Example |
|---|---|---|
| `{ }` | A list | `{"Region", "Product"}` |
| `[ ]` after a name or in an argument | A record of named fields (or a field lookup) | `[Delimiter=","]` |
| `( )` | Function arguments or grouping | `Text.Trim(x)` |
A list of lists, like {{"OrderID", Int64.Type}, {"Amount", type number}}, is a set of pairs. To change a type, edit one inner pair.
The `each` shorthand
You will often meet each, as in this step from an earlier chapter's grouping example:
{{"TotalAmount", each List.Sum([Amount]), type number}}each defines a small function that runs once per row. Inside it, [Amount] means "the Amount field of the current row". It is shorthand for (_) => _[Amount]. If you see _ alone, it means the current item.
Making a small edit
Suppose you want to drop rows where Amount is zero or negative. You can do this with the filter menu, but writing it shows how steps chain. Insert a new step and point in at it:
let
Source = Csv.Document(File.Contents("C:\Data\sales.csv"), [Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.Csv]),
Promoted = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
Typed = Table.TransformColumnTypes(Promoted, {{"OrderID", Int64.Type}, {"Amount", type number}}),
Positive = Table.SelectRows(Typed, each [Amount] > 0)
in
PositiveThree things changed. The new step Positive reads from Typed. The previous comma now sits after Typed. The in line returns Positive. Forgetting any of these is the most common hand-editing mistake.
Other safe, small edits:
- Change a file path. Edit the string inside
File.Contents("..."). - Change a column type. Replace
type numberwithtype textin one pair. - Fix a column name. Correct the string in a rename or type step.
- Remove a step. Delete its line, and make sure no later step still refers to it.
Rules that cause most errors
M is case-sensitive. Table.SelectRows works. Table.selectrows fails. This also applies to column names, so "amount" does not match a column called Amount. Step names are case-sensitive too.
M also needs a comma after every step except the last one. The last step has no trailing comma, because in follows it.
Reordering or deleting steps in the pane can also break a query. Later steps may expect a column that an earlier step created or removed. The editor warns you before it deletes a step with dependents, but not for every case.
Reading error messages
| Message | Likely cause | Fix |
|---|---|---|
| `Expression.Error: The name 'Typed2' wasn't recognized.` | A step name is misspelled or was renamed | Match the name to an existing step |
| `Expression.Error: The name 'Table.selectrows' wasn't recognized.` | Wrong letter case in a function name | Use the exact case, `Table.SelectRows` |
| `Expression.Error: The column 'amount' of the table wasn't found.` | Column name has different case or spacing | Copy the name from the data |
| `Token Comma expected` | A comma is missing between two steps | Add the comma at the end of the earlier step |
| `Token Eof expected` | Extra text after the final expression, such as a trailing comma before `in` | Remove the stray text or comma |
When an error appears, the editor often highlights the failing step in Applied Steps. Click the step just before it to confirm the data was correct up to that point.
Why this matters
Reading M lets you check what a click actually did, fix a path in seconds, and spot why a refresh fails. You do not need to write long M programs. Most real edits are a changed string, a changed type, or one added step.
Exercise
A query ends with these lines. It fails with "The name 'Cleaned' wasn't recognized." What is wrong, and how do you fix it? Typed = Table.TransformColumnTypes(Source, {{"Amount", type number}}), Trimmed = Table.TransformColumns(Typed, {{"Region", each Text.Trim(_), type text}}) in Cleaned
Show answer
The in line returns a step named Cleaned, but no step has that name. The last step is Trimmed. Change the in line to Trimmed, or rename the step to Cleaned in the code and keep the in line as it is.
Exercise
You want to keep only rows where Region equals "West" in a query whose last step is Typed. Write the new step and describe the two other lines you must change.
Show answer
Add Filtered = Table.SelectRows(Typed, each [Region] = "West"). Put a comma after the Typed step so Filtered follows it, and change the in line to return Filtered. The new last step has no trailing comma.