Expert guide

Write Power Query M Code with AI

Let AI handle the syntax while you keep control of the logic

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
    Typed

The ~$ 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

ErrorMeaningFix
Expression.Error: The column 'X' of the table wasn't foundA 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 NumberText in a column typed as numberClean first or use try ... otherwise
Token Comma expected / Token Eof expectedSyntax: missing comma between steps or an extra one before 'in'Every step except the last needs a trailing comma
DataSource.Error: Could not find filePath changed or is user-specificUse a parameter or a cell-based path
Formula.Firewall: Query references other queriesPrivacy levels block combining sourcesSet 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

Yes, and it is one of the better uses of AI for Excel users. M is verbose and its function names are hard to remember, but its logic is predictable. Give the AI your current query from the Advanced Editor and describe the change you want; it usually returns working M that you paste back.

In Excel, open the Power Query Editor (Data → Get Data → Launch Power Query Editor), select the query, then Home → Advanced Editor. The whole query appears as M code that you can copy into an AI chat and paste back after editing.

Column names in M are case-sensitive and must match exactly, including spaces. AI often guesses a name such as 'Order Date' when your column is 'OrderDate'. Paste your real query so the AI can see the actual column names, or ask it to reference columns from the previous step.

For importing, cleaning, reshaping and combining data, yes: it is repeatable, needs no macros and refreshes with one click. VBA is still better for automating actions such as saving files, sending email, or interacting with other applications.

Recent Microsoft 365 versions of Excel for Mac support Power Query, including the editor and many connectors, though some connectors available on Windows are missing. Check your version before building a solution that Mac users must refresh.