Power Query conditional sorting

Scott R

Active Member
Joined
Feb 20, 2002
Messages
493
Office Version
  1. 365
Platform
  1. Windows
I don't want the 'Sorted Rows' statement to error if those columns don't exist.
If none of those columns exist, then I wouldn't sort at all.
Here's what I have so far...

Power Query:
    CheckColumns_D = if Table.HasColumns(Source, {"DY"}) then 1 else 0,
    CheckColumns_P = if Table.HasColumns(Source, {"PER"}) then 2 else 0,
    CheckColumns_Y = if Table.HasColumns(Source, {"YR"}) then 3 else 0,
    #"Sorted Rows" = Table.Sort(Source,{{"YR", Order.Ascending}, {"PER", Order.Ascending}, {"DY", Order.Ascending}}),
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
Do you still want to sort if one or two of them are missing? If so, you could do something like this:

Power Query:
    SortingList = List.Accumulate({"YR", "PER", "DY"}, {}, (s, c)=> if Table.HasColumns(Source, c) then s & {{c,  Order.Ascending}} else s),
    Result = if SortingList = {} then Source else Table.Sort(Source, SortingList)
 
Last edited:
Upvote 0
Solution

Forum statistics

Threads
1,224,823
Messages
6,181,173
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