Sub topic 14
Reading and editing M code
Every click in the Power Query Editor writes a line of M, the language behind Power Query. This chapter assumes you can import data, apply steps in the Editor, and set data types. You will learn to read a query, edit it in the formula bar and Advanced Editor, and avoid common mistakes.
The shape of a query
A query is a let ... in expression. Each line between let and in is a named step. Each step usually uses the step above it as input. The expression after in is the result the query returns. Each name matches an entry in Applied Steps.
let
Source = Excel.CurrentWorkbook(){[Name="SalesRaw"]}[Content],
Typed = Table.TransformColumnTypes(Source, {{"Date", type date}, {"Amount", type number}}),
Trimmed = Table.TransformColumns(Typed, {{"Region", each Text.Trim(Text.Clean(_)), type text}})
in
TrimmedRead it from the top:
Sourcereads the Excel tableSalesRaw.TypedtakesSourceand sets types forDateandAmount.TrimmedtakesTypedand cleans theRegiontext.in Trimmedreturns the last step.
Where to edit
- Formula bar: Select a step in Applied Steps and edit its line. If the bar is hidden, turn it on in the View tab.
- Advanced Editor: On the Home tab, choose Advanced Editor to see and edit the whole query at once.
Rules that cause most errors
- M is case-sensitive.
Text.Trimworks.text.trimdoes not. - Steps are separated by commas. The last step before
inhas no comma. - Names with spaces or symbols need the form
#"Changed Type". - Text is in double quotes. Lists use
{}and records use[]. eachis shorthand for a function of one argument. Inside it,_is the current value, and[Amount]is the Amount field of the current row.
Making a small edit
Suppose you want to keep only large sales. Add a step before in, and point in at it:
let
Source = Excel.CurrentWorkbook(){[Name="SalesRaw"]}[Content],
Typed = Table.TransformColumnTypes(Source, {{"Date", type date}, {"Amount", type number}}),
Large = Table.SelectRows(Typed, each [Amount] >= 1000)
in
LargeTwo details matter here. The new step uses Typed as its input, so it sits in the chain. The in line now names Large. If you forget to update in, your new step is ignored.
Editing safely
- Keep a copy of the query text before large edits. Paste it into a text file.
- Rename a step in the Editor, not by hand, so later steps update their references.
- Reordering steps can break later ones. If a step refers to a column that an earlier change removed, you get an error.
- Read the error message. It usually names the missing column or the unknown name.
Exercise
A query ends with Large = Table.SelectRows(Typed, each [Amount] >= 1000) but the in line still says Typed. What does the query return, and how do you fix it?
Show answer
It returns the table from the Typed step, so no rows are filtered. Change the in line to Large.