Expert guide
Write Power Query M Code with AI
Let AI handle the syntax while you keep control of the logic
Call us at +1 (385) 386-3860
Short answer: build as much of the query as you can with the Power Query ribbon, open Home → Advanced Editor, copy the M code into ChatGPT or Copilot with a precise description of the change, then paste the result back and check each applied step. Always include your real query so the AI uses your actual column names. For imports that must run reliably every week, see Excel data integration and automation.
Power Query is the most underused tool in Excel. It replaces hours of weekly copy, paste and clean-up with a refresh button. Its weakness is the M language underneath: the ribbon covers 80 percent of tasks, and the remaining 20 percent need code that few business users know. That last 20 percent is exactly where AI assistants shine.
The Workflow That Works
1. Use the ribbon first
Connect to the source and do the easy steps with clicks. This gives the AI a correct starting point with your real column names and types.
2. Copy the whole query
Home → Advanced Editor → select all → copy.
3. Describe the change precisely
Say what the output should look like, not just the operation. Include an example row before and after.
4. Paste back and step through
Replace the code in Advanced Editor, click Done, then click each step in Applied Steps to see where the data changes as expected.
5. Ask for comments
Request comments in the code (// lines) so the next person can follow it.
A Good Prompt for M Code
Here is my Power Query M code (Excel 365): [paste query] Change it so that: 1. It loads every .xlsx file in the folder C:\Reports\Branches, not just one file. 2. From each file it takes only the sheet named "Sales". 3. It adds a column "Branch" with the file name without extension. 4. It keeps the existing cleaning steps for each file. Column names are exactly as in my code. Add // comments to each step.
Examples You Can Adapt
Combine all files in a folder with a source column
let
// All Excel files in the folder
Source = Folder.Files("C:\Reports\Branches"),
OnlyXlsx = Table.SelectRows(Source, each [Extension] = ".xlsx"
and not Text.StartsWith([Name], "~$")),
// Read the "Sales" sheet from each workbook
WithData = Table.AddColumn(OnlyXlsx, "Data", each
let wb = Excel.Workbook([Content], true)
in wb{[Item = "Sales", Kind = "Sheet"]}[Data]),
WithBranch = Table.AddColumn(WithData, "Branch",
each Text.BeforeDelimiter([Name], ".")),
Keep = Table.SelectColumns(WithBranch, {"Branch", "Data"}),
Expanded = Table.ExpandTableColumn(Keep, "Data",
{"Date", "Customer", "Amount"}),
Typed = Table.TransformColumnTypes(Expanded,
{{"Date", type date}, {"Amount", type number}})
in
TypedThe ~$ filter skips Excel's temporary lock files, which appear when someone has a workbook open and otherwise crash the refresh. This is a detail AI often omits unless you mention it.
Unpivot a month-per-column report into rows
Unpivoted = Table.UnpivotOtherColumns(Source, {"Product", "Region"},
"Month", "Value"),
MonthAsDate = Table.TransformColumns(Unpivoted,
{{"Month", each Date.FromText("1 " & _), type date}})Budgets and exports often come with Jan, Feb, Mar as columns. Unpivoting turns them into a proper table that PivotTables and formulas can use.
Conditional column with several rules
Tiered = Table.AddColumn(Typed, "Size", each
if [Amount] = null then "Unknown"
else if [Amount] >= 10000 then "Large"
else if [Amount] >= 1000 then "Medium"
else "Small", type text)Replace errors instead of failing the refresh
SafeAmount = Table.AddColumn(Expanded, "AmountClean",
each try Number.From([Amount]) otherwise null, type number)try ... otherwise is M's equivalent of IFERROR. Use it on columns that sometimes contain text like "n/a", and add a step that counts nulls so you notice when it happens.
Merge with a lookup table (left join)
Merged = Table.NestedJoin(Typed, {"Customer"}, Customers, {"Customer"},
"Cust", JoinKind.LeftOuter),
WithManager = Table.ExpandTableColumn(Merged, "Cust", {"AccountManager"})Common M Errors and What They Mean
| Error | Meaning | Fix |
|---|---|---|
| Expression.Error: The column 'X' of the table wasn't found | A step refers to a column name that does not exist (case-sensitive) | Match the exact name from the previous step |
| Expression.Error: We cannot convert the value to type Number | Text in a column typed as number | Clean first or use try ... otherwise |
| Token Comma expected / Token Eof expected | Syntax: missing comma between steps or an extra one before 'in' | Every step except the last needs a trailing comma |
| DataSource.Error: Could not find file | Path changed or is user-specific | Use a parameter or a cell-based path |
| Formula.Firewall: Query references other queries | Privacy levels block combining sources | Set privacy levels in Query Options or restructure into staging queries |
Making Queries Robust for Other People
Store folder paths in a named cell or parameter, not hard-coded in M, so colleagues can point to their own path.
Select columns by name early in the query; extra columns in next month's file will not break anything.
Set data types once, near the end, rather than letting Power Query auto-detect at every step.
Add a final row-count check and show it on a Control sheet.
Name steps meaningfully (FilteredActive, not Filtered Rows 3).
Power Query is the backbone of most Excel data consolidation projects we deliver. When the data lives in SQL Server or another database, queries connect to it directly; see Excel SQL database integration. Unsure whether a task belongs in Power Query or a macro? Read Power Query vs VBA.
FAQ
Power Query M and AI FAQ
Writing and fixing M with ChatGPT and Copilot