A small change to Power Query’s M code can make a big difference. It might remove an unnecessary step, stop a query breaking when a monthly heading changes, or let you perform a transformation that the ribbon does not offer directly.
These 10 Power Query tricks build on familiar tools such as Merge Columns, Group By, and Custom Column. We will use the interface to do the heavy lifting, then adjust the generated code where a little extra flexibility makes all the difference.
For the formulas below, Source represents the previous step. Replace it with the appropriate step name in your query.
What You'll Learn
- Replace hardcoded headings with positional lookups, mapping lists, and dynamically generated expansion lists.
- Transform nested tables before expanding them to align changing monthly column names.
- Extend Group By with distinct text lists and case-insensitive comparisons.
- Simplify custom columns with named calculation steps and directly declared data types.
1. Merge Columns with Line Breaks
Suppose we have separate address, town, and postcode columns. We want to combine them into one Full Address column, with each part on its own line inside the same cell.
We could achieve this with two transformations:
- Select the address columns in the required order.
- Choose Transform > Merge Columns.
- Use a comma as the separator and name the result Full Address.
- Select the merged column and choose Replace Values.
- Find the comma, open Advanced options, enable Replace using special characters, and choose Line Feed as the replacement.
The preview may not look any different. However, selecting a value reveals the separate lines in the cell content preview at the bottom of the editor. Once loaded into Excel, turn on Wrap Text to display those line breaks.
But here is the useful part: Power Query has now shown us how it represents a line feed in M:
"#(lf)"
We can use that directly in the merge transformation. Delete the Replace Values step, return to the merged column formula, and replace the comma separator with "#(lf)".
The result is exactly the same, with one fewer applied step. More importantly, we have used the interface to discover syntax we can reuse.
2. Rename a Column by Position Instead of Name
Monthly column headings are a common source of broken queries. Imagine a table with these three columns:
- Product
- Region
- April 2024
An automatically generated Changed Type step may refer directly to "April 2024". When the source heading becomes May 2024, that step can no longer find the column.
The solution is to give the changing column a stable name before applying transformations that depend on its name.
- Delete the Changed Type step that refers to the monthly heading.
- Rename the third column to Values using the interface.
- Edit the generated rename formula so it retrieves the original name by position.
Table.RenameColumns(
Source,
{{Table.ColumnNames(Source){2}, "Values"}}
)
Table.ColumnNames(Source) returns a list of the table’s column names. The {2} selects the third item because Power Query uses zero-based indexing:
- First column:
{0} - Second column:
{1} - Third column:
{2}
Now we can select the columns and use Detect Data Type. Any subsequent reference to the third column uses the stable name Values rather than a changing month.
This approach works when the column’s position stays consistent, even though its heading changes.
3. Rename Columns Inside Nested Tables Before Expanding
The same problem becomes more interesting when we connect to a workbook containing several monthly worksheets.
Our April, May, and June worksheets each contain Product and Region, but their third columns are named April 2024, May 2024, and June 2024. These worksheets appear as nested tables in the Data column.
If we expand them immediately, Power Query creates a separate column for each monthly heading. What we actually want is one Values column, with the monthly records stacked underneath each other.
We need to rename the third column inside every nested table before expanding.
Use the interface to generate the structure
There is no need to remember the entire formula. We can borrow the structure of another transformation:
- Select the outer table’s Name column.
- Choose Transform > Extract > First Characters.
- Enter 1 and confirm.
- Edit the resulting
Table.TransformColumnsformula.
That temporary extraction gives us the syntax for transforming every value in a column. Change the target column to Data, replace the extraction with our rename formula, and declare the output as type table.
Table.TransformColumns(
Source,
{
{
"Data",
each Table.RenameColumns(
_,
{{Table.ColumnNames(_){2}, "Values"}}
),
type table
}
}
)
The important adjustment is replacing the references to Source inside the rename operation with _. Within this transformation, the underscore represents the current nested table, not the entire outer table.
Each nested table now contains Product, Region, and Values. Expand Data, and the values from all three months fall into the same column.
This technique of generating a transformation through the interface, then reusing its structure, is a handy way to build M code without starting from a blank formula bar.
4. Rename Nested Columns Using a Mapping List
Renaming by position is useful, but what happens if the monthly column moves? In that situation, we can use a mapping table containing the old and new names instead.
Create a separate query with two columns:
- Old Name: The headings to look for, such as April 2024, May 2024, and June 2024.
- New Name: The replacement heading, Values, for each corresponding row.
In the example formula below, that mapping query is named RenameMap.
Table.RenameColumns needs a list of rename pairs. We already have two lists, one from each mapping column. List.Zip pairs their corresponding items together.
List.Zip({
RenameMap[Old Name],
RenameMap[New Name]
})
This turns the two mapping columns into the structure required by the rename function: the first old name paired with the first new name, the second with the second, and so on.
There is one catch. The April table does not contain a May 2024 column. If we try to apply every rename pair to every nested table, the missing headings produce errors.
Add MissingField.Ignore as the optional third argument to Table.RenameColumns:
Table.TransformColumns(
Source,
{
{
"Data",
each Table.RenameColumns(
_,
List.Zip({
RenameMap[Old Name],
RenameMap[New Name]
}),
MissingField.Ignore
),
type table
}
}
)
Now each nested table applies the mappings for headings it contains and ignores the others. Unlike the previous method, this does not depend on the monthly column being in a particular position.
5. Expand Nested Tables Without Hardcoding Column Names
Sometimes we want the opposite result: April, May, and June should remain separate columns.
We can expand Data through the interface, using Load more if necessary to find all the available headings. However, the generated Table.ExpandTableColumn formula contains a fixed list of column names.
When July or August appears, those new headings are not automatically added to that list.
To make the expansion dynamic, combine two functions:
Table.Combinecombines the nested tables.Table.ColumnNamesretrieves the column names from that combined result.
Table.ExpandTableColumn(
Source,
"Data",
Table.ColumnNames(Table.Combine(Source[Data]))
)
Source[Data] supplies the list of nested tables. Combining them lets us obtain the column names across the whole set, rather than relying on one worksheet’s headings.
When editing the interface-generated formula, remove the optional fixed list of output column names as well. Otherwise, part of the expansion still depends on a hardcoded list.
We now get the existing monthly columns without naming them individually, and newly arriving month columns can be included on refresh.
6. Combine Text into One Cell with Group By
Suppose our data contains Product, Region, and Value. We want one row per product, showing both the total value and a comma-separated list of its regions.
The Group By dialog can create the total, but its aggregation options do not include a text-combine operation. We can still use it to generate most of the formula.
- Select Product and choose Transform > Group By.
- Switch to Advanced.
- Add Total Value using Sum on the Value column.
- Add Region List, temporarily using Sum on the Region column.
- Confirm the dialog.
The Region List calculation produces an error because the regions are text. That is expected. In the generated formula, replace its List.Sum operation with Text.Combine, using a comma and a space as the separator.
For a list containing each region only once, wrap the Region list in List.Distinct:
Table.Group(
Source,
{"Product"},
{
{"Total Value", each List.Sum([Value]), type nullable number},
{
"Region List",
each Text.Combine(List.Distinct([Region]), ", "),
type nullable text
}
}
)
Without List.Distinct, a region such as North can appear more than once in the same cell. With it, we get one instance of each region while keeping the total value calculation alongside it.
The ribbon gives us a starting point, not a limit on what the transformation can do.
7. Group Data Without Treating Case as Different
The previous grouping works well until the Product column contains inconsistent capitalization. Power Query normally treats uppercase and lowercase variations as different grouping keys.
If those variations should represent the same product, we can change the comparison used by Table.Group.
After the list of aggregations, add:
null,
Comparer.OrdinalIgnoreCase
The complete grouping pattern becomes:
Table.Group(
Source,
{"Product"},
{
{"Total Value", each List.Sum([Value]), type nullable number},
{
"Region List",
each Text.Combine(List.Distinct([Region]), ", "),
type nullable text
}
},
null,
Comparer.OrdinalIgnoreCase
)
The null leaves the group-kind argument at its default. Comparer.OrdinalIgnoreCase tells Power Query to ignore capitalization when comparing the product grouping keys.
We can now group those product variations together without first adding a separate uppercase or lowercase transformation.
8. Retrieve a Report Header Cell by Position
A report is not always a neatly structured table. A debtors report, for example, might show customer names and outstanding balances in the body, while its report date appears in a cell near the top.
We want that date repeated in a separate column beside every customer. The trick is to retrieve it from an earlier step, even after we have cleaned up the report body.
- Filter out the blank or unwanted report rows.
- Promote the appropriate row to headers.
- Return briefly to Source and identify the report date’s original position.
- Go back to the latest step and choose Add Column > Custom Column.
- Name the column Date and reference the original cell.
In this example, the report date is in Column1, on the second row of Source:
Source[Column1]{1}
[Column1] retrieves that column as a list. {1} retrieves its second item, again using zero-based indexing.
Because the expression points to a specific cell in Source rather than the current customer row, it supplies the same report-header text for every row.
To finish:
- Select the new Date column.
- Choose Transform > Extract > Text After Delimiter.
- Use a colon followed by a space as the delimiter.
- Change the column’s data type to Date.
The report date is now part of the structured output, even though it originally sat outside the main data area.
9. Break a Complex Custom Column into Multiple Steps
A custom column does not have to contain one enormous nested expression. If we need to transform a reference using several rules, we can break the calculation into named steps inside the custom column itself.
The structure uses let and in, just like a complete Power Query query:
- Start the custom column formula with
let. - Give the first calculation a name and assign its expression with an equals sign.
- Separate each named calculation with a comma.
- Reference earlier calculations by name in later calculations.
- Do not place a comma after the final calculation.
- Finish with
in, followed by the name of the calculation to return.
For example, a calculation named Step3 can use the results of Step1 and Step2. Placing Step3 after in makes its result the custom column’s output.
In our reference transformation, the final calculation is named Return, so the expression finishes with in Return.
These are steps within the column’s calculation, not separate Applied Steps. We can keep a complicated formula together while making its individual parts much easier to follow.
10. Declare a New Column’s Data Type When Adding It
After creating a custom column, its data type is typically Any. The usual next action is to change it to Text, which creates a separate Changed Type step.
We can declare the type directly in the Table.AddColumn transformation instead.
- If a separate Changed Type step already exists for the new column, note its required type and delete that step.
- Select the Added Custom step.
- At the end of the
Table.AddColumnformula, before its closing parenthesis, add a comma followed bytype text. - Commit the formula.
For the multi-step formula from the previous tip, this means the column calculation finishes with in Return, followed by , type text as the final argument to Table.AddColumn.
The New Reference column is now declared as Text in the same step that creates it. There is no need for another applied step just to assign that type.
Small M Code Changes, More Flexible Queries
The common thread through these tricks is simple: let the Power Query interface generate useful code, then adapt it to fit the job.
That might mean replacing a fixed monthly heading with a positional lookup, transforming nested tables before expanding them, or adding an optional argument that the dialog does not expose. You do not have to write every query from scratch to make good use of M.
Start with the trick that solves a problem in your own workbook. A few well-placed changes can make your Excel automation easier to maintain and less dependent on manual fixes.
To practise with the example workbook, join the free Insiders program and look for file reference 0212 Power Query M code tricks.zip. For more structured training, explore the Excel automation academy.


