Rename columns based on position
If some of the column names in the source data change every month, Power Query will generate a column wasn’t found error.
Column names can be renamed based on position rather than name.
This is done by embedding the Table.ColumnNames function inside the Table.RenameColumns function.
In this example data, the month name forms part of some column headings.
Each month the column headings change.
This will generated an error in Power Query when the data is refreshed.
Instead the column is going to be renamed based on position.
Load the data into Power Query.
Double click on the column heading and change the name.
A step with the Table.RenameColumns function will be added.
= Table.RenameColumns(#"Changed Type",{{"Sales to July", "Sales (YTD)"}, {"Profit to July", "Profit (YTD)"}})
Click in the Formula bar to edit the step.
Replace the column name portion of the function with:
Table.ColumnNames(PREVIOUS STEP NAME){COLUMN NUMBER}
Power Query uses a zero base. This makes the first position value zero, the second position value is one and so on.
This applies to columns and rows
In the example, the previous step is #“Changed Type”.
The column is the second column. Its position/number is one (two minus one).
= Table.RenameColumns(#"Changed Type",{{Table.ColumnNames(#"Changed Type"){1}, "Sales (YTD)"}, {Table.ColumnNames(#"Changed Type"){2}, "Profit (YTD)"}})
Next month when the second columns heading changes from Sales to July to Sales to August, it will consistently be renamed to Sales (YTD) by Power Query.