M code function syntax follows the pattern FunctionName(argument1, argument2, ...), where each argument is separated by a comma and the entire call is wrapped in parentheses. For example, Text.Upper("hello") returns "HELLO". This is the core structure you will use in Power Query’s M language, which powers data transformation in Excel and Power BI.
What Is M Code and Why Does Syntax Matter?
M is the formula language used in Power Query (Get & Transform) in Excel and in Power BI’s Query Editor. It is a functional, case-sensitive language where every expression returns a value. Unlike Excel’s worksheet formulas, M is not entered into cells; it is written in the Advanced Editor or in custom columns within Power Query. Syntax errors are common for beginners because M is strict about capitalization, commas, and parentheses. A single missing comma can stop a query from running.
The Basic Function Call Structure
Every M function call has three parts: the function name, parentheses, and arguments inside those parentheses. The function name must match exactly, including case. For instance, Text.Trim is correct, but text.trim will fail. Arguments are separated by commas. Some functions have optional arguments, which you can omit by leaving the spot empty or by using the null keyword. Here are a few examples:
List.Sum({1, 2, 3})returns 6.Date.Year(#date(2024, 5, 1))returns 2024.Table.AddColumn(Source, "NewCol", each [Column1] * 2)adds a column.
Notice that some functions, like Table.AddColumn, take a table as the first argument. The each keyword is a shorthand for a function that applies to each row.
How to Write a Function in M (Lambda Syntax)
You can also define your own functions in M using the syntax (parameter1 as type, parameter2 as type) => expression. The arrow => separates parameters from the body. For example, a function that doubles a number looks like this: (x as number) => x * 2. You can assign it to a name in a let expression:
let
Double = (x as number) => x * 2,
Result = Double(5)
in
Result
This returns 10. The type annotation as number is optional but helps with error checking. If you omit it, M will try to infer the type from usage.
Common Syntax Errors and How to Fix Them
Most M syntax errors fall into a few categories. One is mismatched parentheses: every opening parenthesis must have a closing one. Another is using the wrong case, such as text.upper instead of Text.Upper. A third is forgetting commas between arguments, especially in functions like Table.AddColumn where the second argument is a column name and the third is the expression. Here is a typical error:
// Incorrect: missing comma after "NewCol"
Table.AddColumn(Source, "NewCol" each [Column1])
// Correct:
Table.AddColumn(Source, "NewCol", each [Column1])
Another common mistake is using Excel’s IF syntax instead of M’s if ... then ... else. In M, it is if [Column] > 5 then "High" else "Low"—note the lowercase if and the then and else keywords.
How to Choose the Right Function and Syntax
When you need a specific transformation, first check if a built-in function exists. The M function library is organized by category, such as Text, List, Table, Date, and Number. For example, to combine text, use Text.Combine; to sum a list, use List.Sum. If no built-in function fits, write a custom function using the lambda syntax. A good rule is to start with the simplest expression that works. For instance, to filter rows, use Table.SelectRows with a condition:
Table.SelectRows(Source, each [Age] > 18)
Here, each is a compact way to write (row) => row[Age] > 18. You can use either form; each is more concise but less explicit.
M Code vs. Excel Formulas: Key Differences
If you are used to Excel worksheet formulas, M will feel different in several ways. First, M is case-sensitive, while Excel functions are not. Second, M uses #date, #time, and #datetime to create date and time values, whereas Excel uses DATE(). Third, M does not use cell references; it works with columns and tables. For example, to reference a column in M, you write [ColumnName], not A1. Fourth, M has no IFERROR; instead, you use try ... otherwise. For example:
try Number.FromText([TextColumn]) otherwise null
This attempts to convert text to a number and returns null if it fails. Understanding these differences helps you avoid transferring bad habits from Excel.
Frequently Asked Questions
Why does my M code say “Expression.Error: Invalid identifier”?
This usually means you used a reserved word or an invalid name. M identifiers cannot contain spaces or start with a number. If you need a column name with a space, wrap it in #"Column Name". For example, Table.Column(Source, #"First Name"). Also, avoid using M keywords like each or let as variable names.
Can I use M code in Excel cells?
No. M code only runs inside Power Query’s query editor. To use it, go to Data > Get Data > Launch Power Query Editor. You can write M in the Advanced Editor or in custom column formulas. Excel worksheet cells use a different language (DAX for measures, and standard Excel formulas for cells).
How do I comment in M code?
You can use // for a single-line comment and /* ... */ for multi-line comments. Comments are ignored by the engine. For example, // This is a comment or /* This is a.
multi-line comment */
What is the difference between each and a full function?
each is a shorthand that automatically adds a parameter named _ (or the row). Writing each [Column] + 1 is equivalent to (row) => row[Column] + 1. Use each for simple expressions; use a full function when you need multiple parameters or a more complex body.
Why does my query fail when I use a comma inside a string?
Commas inside double quotes are fine; M treats them as part of the string. The problem usually arises when you forget to close the string or when you use a comma as a decimal separator in a locale that expects a period. Always use periods for decimal numbers in M, regardless of your system locale.
Practical Example: Building a Custom Function
Suppose you want a function that calculates the area of a rectangle. You can define it in a query:
let
Area = (length as number, width as number) => length * width,
Result = Area(5, 3)
in
Result
This returns 15. To reuse this function across queries, you can create a blank query and paste the function definition, then reference it from other queries. This is a common pattern for reusable logic in Power Query.
Related
- What Does Data Entry Consist Of?
- Random Number Gen C++: How to Generate Random Numbers
- Shortcut for Deleting in Excel: Top 5 Ways
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- VLOOKUP and HLOOKUP Together: How to Combine ThemYes, you can use VLOOKUP and HLOOKUP together in a single formula, but the practical way to do…
- Link Different Sheets in Excel with FormulasTo link a cell on one Excel sheet to a cell on another, enter a reference such as…
- Filter Duplicates in Excel: Find, Keep, or Remove ThemYes. In Excel for Microsoft 365 on Windows, you can filter duplicate records by adding a helper column…
- Excel LAMBDA Function Examples for Reusable FormulasExcel LAMBDA lets you turn a formula into a reusable function: define it with =LAMBDA(parameters, calculation), save it…
- VLOOKUP in Excel: Step-by-Step GuideTo use VLOOKUP in Excel, put the value you want to find in the first column of a…
- Excel COUNTIF Criteria: Rules, Examples, and FixesIn Excel, COUNTIF criteria are the conditions that tell the COUNTIF function which cells to count. The syntax…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.