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

Back into an answer in Excel
Use Data, What-If Analysis, Goal Seek to find the correct input cell value to reach a desired result
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,224,819
Messages
6,181,153
Members
453,021
Latest member
Justyna P

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