Power Query: Sort Table Columns Using a List

takoyaki

New Member
Joined
Oct 24, 2022
Messages
30
Office Version
  1. 365
Platform
  1. Windows
Hi all,

This should be easy but I'm having some trouble with the syntax. I'm trying to sort multiple columns in ascending order in my table. It's easy enough to manually click each column and sort it in descending order, but then my M-code is hard-coded to these column header names. If the header names change, the code will break.

Manually sorting each column:

Power Query:
Table.Sort(PreviousStep,{{"Column1", Order.Ascending}, {"Column2", Order.Ascending}, {"Column3", Order.Ascending}, {"Column4", Order.Ascending}})

I have a list that dynamically populates the correct headers. What is the correct way to write the statement below?

Dynamically sorting each column according to my list, HeaderstoSort:

Power Query:
Table.Sort(PreviousStep,{HeaderstoSort, Order.Ascending})
 

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type
Power Query:
SortList = List.Transform(HeaderstoSort, each {_}),
Result = Table.Sort(PreviousTableName,SortList)

if you wanted Order.Descending you would need to include that like

Power Query:
SortList = List.Transform(HeaderstoSort, each {_, Order.Descending}),
Result = Table.Sort(PreviousTableName,SortList)
 
Upvote 0
Solution
Power Query:
SortList = List.Transform(HeaderstoSort, each {_}),
Result = Table.Sort(PreviousTableName,SortList)

if you wanted Order.Descending you would need to include that like

Power Query:
SortList = List.Transform(HeaderstoSort, each {_, Order.Descending}),
Result = Table.Sort(PreviousTableName,SortList)
Thank you SO MUCH! You're the MVP!
 
Upvote 0

Forum statistics

Threads
1,215,104
Messages
6,123,113
Members
449,096
Latest member
provoking

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top