Skip to content

Dynamically removing columns

This page shows how to remove unwanted columns without naming the columns to keep. The query works out which columns have headers each time it runs, which helps when columns move or when new ones are added to the source over time.

The data sits in a named range called Data, which covers more columns and rows than the data fills:

An Excel sheet with Name, Country and Age in columns A to C, and the New Name dialog defining the range Data as Sheet1!$A$1:$I$18

The named range

Loaded into Power Query with Excel.CurrentWorkbook(), the range arrives as a table inside the Content column, with nine columns named Column1 to Column9:

The Source step showing one row whose Content is a table, with a preview of that table below it, where only Column1 to Column3 hold data and the rest are null

Only the first three columns are wanted. Table.SelectColumns could pick them, but it would need their names written into the query, so if the columns moved, or if a new one were added, the query would not follow.

The alternative is to build the list of columns from the data itself:

  • Use Table.Combine on the Content column, which joins all the tables it holds into one. Here there is only one table, so this simply expands it:

The formula Table.Combine(Source[Content]) and the resulting table, with Name, Country and Age in the first row of Column1 to Column3

  • Wrap the formula in Table.PromoteHeaders, so the first row becomes the headers. The empty columns keep their default names, such as Column4 and Column5:

The formula Table.PromoteHeaders(Table.Combine(Source[Content])), with the columns now headed Name, Country, Age, Column4 and Column5

  • Wrap that in Table.ColumnNames, which returns the headers as a list. Name this step ColNames:

A list of nine column names, Name, Country and Age followed by Column4 to Column9, in a step named ColNames

  • Filter the list with List.Select to drop any name that contains Column, any name that is a space or empty, and any null. Name this step FilteredCols. The test can be anything that suits the data:

The formula List.Select over ColNames, keeping items that do not contain Column and are not a space, empty or null, which leaves Name, Country and Age

  • Only now, once the list has been filtered, use Table.SelectColumns to keep the columns named in FilteredCols. Name this step FinalTable:

The formula Table.SelectColumns(Table.PromoteHeaders(Table.Combine(Source[Content])), FilteredCols), returning just the Name, Country and Age columns

To test the query, add a new field to the range in column E, leaving column D empty:

The Excel sheet with a New Field heading in E1 and the values 1 to 8 beneath it, and column D left blank

The named range with a new field

After a refresh, and with no change to the query, New Field appears as a fourth column, while the empty columns D and F to I stay out:

The query result with columns Name, Country, Age and New Field