VBA - Sorting Multiple Columns by Header's Names

AndrewBR

New Member
Joined
Apr 16, 2018
Messages
2
Hi Guys! I have the code below to sort my table, but this sheet is downloaded from a system and the columns change position from time to time.

Is there a way to execute the code below using header's names?

Code:
Range("A1").CurrentRegion.Sort _
   key1:=Range("AY1"), Order1:=xlAscending, _
   key2:=Range("AZ1"), order2:=xlAscending, _
   key3:=Range("BV1"), order3:=xlAscending, _
   Header:=xlYes

Like this:

Code:
Range("A1").CurrentRegion.Sort _
   key1:=Range("[B]CPO Number[/B]"), order1:=xlAscending, _
   key2:=Range("[B]CPO Item[/B]"), order2:=xlAscending, _
   key3:=Range("[B]Invoice Number[/B]"), order3:=xlAscending, _
   Header:=xlYes

I've been reading this forum for a long time, but this is my first post!


I'd a research and haven't find anything.


I really appreciate any help you can provide. :biggrin:
 

Excel Facts

When did Power Query debut in Excel?
Although it was an add-in in Excel 2010 & Excel 2013, Power Query became a part of Excel in 2016, in Data, Get & Transform Data.
Hi & welcome to MrExcel
How about
Code:
Sub cols()
   Dim Fnd(1 To 3) As Range
   Dim Ary As Variant
   Dim i As Long
   
   Ary = Array("CPO Number", "CPO Item", "Invoice Number")
   For i = 1 To 3
      Set Fnd(i) = Range("1:1").find(Ary(i - 1), , , xlWhole, , , False, , False)
   Next i
   Range("A1").CurrentRegion.Sort _
   key1:=Fnd(1), order1:=xlDescending, _
   key2:=Fnd(2), order2:=xlAscending, _
   key3:=Fnd(3), order3:=xlAscending, _
   header:=xlYes
      
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,244
Messages
6,170,976
Members
452,372
Latest member
Natalie18

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