Using ‘M’ to dynamically filter rows
This page shows how to filter rows dynamically with M, so that a query keeps the right rows even when their position in the source changes.
Why M helps here
Section titled “Why M helps here”Most of Power Query can be used without writing any M, which is the language behind every step. Some problems, though, can only be solved by editing the M that the interface writes, and this is one of them.
M uses a handful of characters that are worth knowing before reading the code below:
| Characters | What they do |
|---|---|
(parameters) |
Enclose the parameters of a function |
{list} |
Enclose the items of a list |
[record] |
Enclose a record, or name a field or column |
"text" |
Enclose a text value |
#"Step Name" |
Refer to a step whose name contains spaces or other reserved characters |
// comment |
Mark the rest of a line as a comment |
/* comment */ |
Mark a comment that spans several lines |
The problem
Section titled “The problem”The source is a text file laid out like this:

The rows that matter sit in the middle of the file, and their position is not fixed:
- The number of rows above the ID Number header row can change, so there could be five rows above it or five thousand.
- The number of rows between the header and the ID Total row, and the number below ID Total, can also change.
The main task is therefore to extract the rows between the two markers wherever they fall. A second task is to work out, for each order, how many days have passed since the order before it.
1. Find the rows that mark the start and the end
Section titled “1. Find the rows that mark the start and the end”The first job is to find the row numbers of the two marker rows:
- Open a blank Excel workbook.
- Create a new query from a text file: choose From File, then From Text, pick the file and click Transform Data.
- On the Add Column tab, choose Index Column and then From 0.
- On Column1, choose Text Filters and then Begins With.
- Set the filter to keep rows that begin with ID Number or begin with ID Total.
The query now returns just two rows, each with its index:

These two numbers are found afresh on every refresh, so however many rows come before, between or after the markers, the query still finds the right ones.
2. Combine the two steps into one
Section titled “2. Combine the two steps into one”Open the Home tab and choose Advanced Editor, where the two steps read as follows:
#"Added Index" = Table.AddIndexColumn(Source, "Index", 0, 1), #"Filtered Rows" = Table.SelectRows(#"Added Index", each Text.StartsWith([Column1], "ID Number") or Text.StartsWith([Column1], "ID Total"))Replace the reference to #“Added Index” inside the #“Filtered Rows” step with that step’s own formula, and rename #“Filtered Rows” to RowNumbers, so that one step remains:
RowNumbers = Table.SelectRows(Table.AddIndexColumn(Source, "Index", 0, 1), each Text.StartsWith([Column1], "ID Number") or Text.StartsWith([Column1], "ID Total"))3. Keep the rows between the markers
Section titled “3. Keep the rows between the markers”With RowNumbers selected in Applied Steps, click the fx button beside the formula bar. This adds a step called Custom1, which by default points at the step before it:
= RowNumbersChange the formula so that it points back at the original data:
= SourceNext, cut the data off at the ID Total row. On the Home tab, choose Keep Rows, then Keep Top Rows, and enter 9. The preview now shows the first nine rows only:

The 9 is fixed, so it has to be replaced with the position that RowNumbers found. Change the Kept First Rows formula from this:
= Table.FirstN(Custom1, 9)to this:
=Table.FirstN(Source, RowNumbers[Index]{1})RowNumbers[Index]{1} reads the second value in the Index column, which is the row number of ID Total. Because the formula now refers to Source directly, the Custom1 step is no longer needed and can be deleted:

Then remove the rows above the header in the same way:
- On the Home tab, choose Remove Rows, then Remove Top Rows, enter 4 and click OK.
- Change the formula from this:
= Table.Skip(#"Kept First Rows",4)- to this, which reads the row number of ID Number from RowNumbers:
= Table.Skip(#"Kept First Rows", RowNumbers[Index]{0})These last two steps can also be combined:
- Open the Advanced Editor from the Home tab, where the two steps read as follows:
#"Kept First Rows" = Table.FirstN(Source, RowNumbers[Index]{1}), #"Removed Top Rows" = Table.Skip(#"Kept First Rows", RowNumbers[Index]{0})- Put the #“Kept First Rows” formula inside the second step, and rename that step to ExtractRows:
ExtractRows = Table.Skip(Table.FirstN(Source, RowNumbers[Index]{1}), RowNumbers[Index]{0})- Click Done.
The query now has three steps, and its result starts at the header row and ends at the last order:

4. Split the data into columns
Section titled “4. Split the data into columns”Each row is still a single line of text, so split it into columns and set their types:
- On the Transform tab, choose Split Column, then By Delimiter, choose Tab and At each occurrence of the delimiter, and click OK.
- Delete the Changed Type step that Power Query adds automatically, because it sets every column to text, which is not what the data needs once the headers are in place.
- On the Transform tab, choose Use First Row as Headers.
- Right-click ID Number, choose Change Type and then Whole Number.
- Do the same for Amount.
- Right-click OrderDate, choose Change Type and then Date.
The data is now a proper table:

5. Compare each order with the one before
Section titled “5. Compare each order with the one before”The last task is to count the days since the previous order. This needs a way to read a value from the row above, which an index makes possible:
- Add an index column that starts at 0, as before.
- Rename the Added Index step to Transactions:

Now add a custom column:
- On the Add Column tab, choose Custom Column.
- Name the column PreviousOrder.
- Enter this formula:
= try Transactions[OrderDate]{[Index]-1} otherwise [OrderDate]The formula reads the OrderDate column of the Transactions step as a list, and picks the item one position above the current row’s index. The first row has no row above it, so the lookup fails there, and try … otherwise returns the row’s own OrderDate instead.
To count the days between the two dates:
- Select the OrderDate column, hold down Ctrl and select the PreviousOrder column.
- On the Add Column tab, choose Date and then Subtract Days.

Finally, tidy up:
- Right-click the Index column and choose Remove.
- Right-click the PreviousOrder column, choose Change Type and then Date.
- Right-click the Subtraction column, choose Rename and enter DaysSinceLastOrder.
- On the Home tab, choose Close & Load.
The result on the worksheet looks like this:

This example follows one in Ken Puls and Miguel Escobar’s M is for (Data) Monkey (Holy Macro! Books).