Changing a column name in the Power BI Query Editor without hardcoding

Home Power BI Query Editor Changing a column name in the Power BI Query Editor without hardcoding

Sometimes, when you enter data into the query editor, you need to change the name of a column that is not always the same in the source. This is one of those cases where the UI won't help much: by double-clicking on the column header and changing it to whatever you want, the column name will be hard-coded as it comes in. If in a new data refresh the column name is different, the query will break. Therefore, you will have to write some M yourself. Or steal the code below from me 😉

Here it is:

= Table.RenameColumns (

The table you want to refer to, usually the previous step in your query,

{{ Table.ColumnNames ( The same table again ) { The number of the column },

"The new column name" }}

)

And if you want to change the order of your columns dynamically, don't just move them around using the UI either. That will hard code all of the column names in your table. This is the code you want to use instead:

Table.ReorderColumns (

The table you want to refer to which usually is the previous step in your query,

List.InsertRange (

List.Difference (

Table.ColumnNames ( The same table again ),

{ "Columnname you want to move1" , "Columnname you want to moveN"}

),

The columnnumber you want to move the columns to,

{ "Columnname you want to move1" , "Columnname you want to moveN"}

)

)