Proper M code syntax ensures your Power Query queries run without errors and produce expected results. M is the formula language behind Power Query in Excel and Power BI, used to transform data. Correct syntax matters because even small mistakes—like missing parentheses or incorrect case—cause failures. This guide walks you through writing valid M code step by step, using real-world examples. You’ll need access to Power Query Editor in Excel (2016 or later) or Power BI Desktop.

What You'll Need

  • Microsoft Excel 2016 or later (with Power Query add-in enabled), or Power BI Desktop installed
  • A data source to query (e.g., Excel table, CSV file, or database)
  • Basic understanding of column names and data types in your source

Step-by-Step

  1. Open your Excel workbook or Power BI report, then go to the Data tab (Excel) or Home tab (Power BI) and select Get Data > From File > From Excel/From Text/CSV (or another source). After loading the preview, click Transform Data to open Power Query Editor.
  2. In Power Query Editor, locate the Advanced Editor. In Excel, it’s under the Home tab > Advanced Editor; in Power BI, it’s in the Home tab > Advanced Editor. Click it to open the code window where you’ll write or edit M code.
  3. Start with the basic query structure: every query begins with let , defines steps using Source , Saved , or custom names, and ends with in followed by the final step. For example, to read a CSV file, write: let Source = Csv.Document(File.Contents("C:\data\sales.csv"),[Delimiter=",", Columns=3, Encoding=65001, QuoteStyle=QuoteStyle.None]), PromotedHeaders = Table.PromoteHeaders(Source, [PromoteAllScalars=true]), in ChangedType Note that each line (except the last) ends with a comma, and the final line before in has no comma.
  4. Use correct case for keywords: let, in, Source, Table.PromoteHeaders, and Table.TransformColumnTypes must be spelled exactly as shown—M is case-sensitive. Mis-typing Table.promoteHeaders (with lowercase p) will throw an error.
  5. Reference columns by name in functions using double quotes. For example, to filter rows where the "Sales" column exceeds 100, add a step: FilteredRows = Table.SelectRows(ChangedType, each [Sales] > 100) Ensure the column name matches exactly (including spaces and capitalization) as it appears after header promotion.
  6. To add comments, start a line with //. M ignores everything after // on that line. For multiline comments, wrap text in /* ... */. Example: // Filter high-value sales FilteredRows = Table.SelectRows(ChangedType, each [Sales] > 100)
  7. Test your query by clicking Close & Load. If there’s a syntax error, Power Query highlights the problematic line in red and displays a descriptive error message in a pop-up window. Fix the issue in Advanced Editor and re-run.

Common Mistakes

Mistakes often arise from overlooking M’s strict formatting rules. First, forgetting commas between steps—every line in the let block except the last one must end with a comma. Omitting it causes a "Token Comma expected" error. Second, mixing up single and double quotes: column names and text literals use double quotes (e.g., "Sales"), while character literals (rarely used) use single quotes. Using 'Sales' instead of "Sales" leads to a syntax error.

Third, misnaming steps: Source, PromotedHeaders, and ChangedType are just variable names—you can rename them, but consistency matters. If you rename Source to MySource but forget to update references like Table.PromoteHeaders(Source, ...), the query fails because Source no longer exists.

Fourth, incorrect data type names. Use type date, type text, and Int64.Type (with a dot), not integer or datetime. Power Query uses specific type identifiers, and deviations trigger "Type expected" errors.

Fifth, incomplete function arguments. Functions like Csv.Document require a list of options in square brackets (e.g., [Delimiter=",", ...]). Missing brackets or equals signs causes parsing failures.

Tips

Use the Query Editor’s built-in UI to generate M code first, then refine it manually. For example, to filter rows, click the filter icon on a column header—Power Query writes the correct Table.SelectRows call. You can then copy that code into Advanced Editor for reuse or modification. This avoids syntax errors from scratch.

Indent steps consistently (e.g., four spaces per level) to improve readability. This helps spot missing commas or mismatched parentheses quickly. Also, break complex transformations into named steps instead of nesting functions. Instead of writing Table.SelectRows(Table.TransformColumnTypes(Source, ...), each ...), define intermediate steps like Transformed and Filtered separately.

Enable Auto-detect Types in Power Query Editor (File > Options > Current User > Data Load Settings > Enable automatic detection of data types). This reduces manual type conversions and helps match expected data types in your M code.

Use the Formula Bar (visible by default in Excel) to preview step outputs. After creating a step, click it in the Applied Steps pane—the Formula Bar shows the result of that step. This helps verify intermediate logic without running the full query.

Troubleshooting

If your query fails, start with the simplest checks. First, verify the data source path is correct and accessible. If using File.Contents("C:\data\sales.csv"), ensure the file exists at that location and your account has read permissions. Network paths must be mapped consistently across devices.

Second, check for unmatched parentheses or brackets. M code requires balanced (), [], and {}. A missing closing parenthesis in Csv.Document(...) causes a "Token Eof expected" error. Count brackets using the editor’s bracket-matching highlight (click next to a parenthesis to see its pair).

Third, look for invisible characters. Copying code from websites or PDFs can introduce non-printing characters (e.g., smart quotes instead of straight quotes). Delete and retype quotes and commas manually in Advanced Editor to eliminate this.

Fourth, if column names contain spaces or special characters (e.g., "Sales Amount!"), reference them with #"Sales Amount!"—the # prefix escapes non-standard names. Without it, Power Query treats the name as invalid syntax.

Fifth, restart Power Query Editor or Excel/Power BI Desktop if errors persist. Temporary glitches can corrupt the query state. Save your work first, then close and reopen the application.

Frequently Asked Questions

Can M code handle conditional logic?

Yes. Use if ... then ... else ... statements. Example: AddedCustom = Table.AddColumn(PromotedHeaders, "Category", each if [Sales] > 500 then "High" else "Low").

Why does my query work in Power BI but not Excel?

Differences in Power Query versions or available connectors can cause issues. Ensure both tools are updated. Some data sources (e.g., Azure SQL) require additional drivers in Excel that may be pre-installed in Power BI.

How do I reference a previous step’s output in a new step?

Use the step’s name directly. If you named a step FilteredRows, the next step can start with Custom1 = Table.Sort(FilteredRows, {"Sales", Order.Descending}).

Is there a limit to how many steps I can add?

No hard limit, but too many steps slow performance. For large datasets, consolidate operations (e.g., combine filtering and column renaming into one Table.TransformColumns call) to reduce overhead.

Can I use functions from other languages in M code?

Not directly. M is self-contained, but you can call R or Python scripts via the R/Python integration in Power BI (not Excel). This requires installing those languages separately.

What happens if I delete the in keyword?

The query fails with "Token In expected". The in clause defines the final output step—without it, Power Query doesn’t know which step’s result to return.