How to do a basic sort with headers from VBA

OaklandJim

Well-known Member
Joined
Nov 29, 2018
Messages
855
Office Version
  1. 365
Platform
  1. Windows
Team XLNT

I am trying to do a basic sort with VBA. I have a data range with headers. I tried to adapt code that I found on line but the headers get sorted with the data. Not what I need! My hack-code is shown below. I set the "all data" range needed by getting the current region using one of the headers. What do I need to do to sort the two keys without headers sorting too? I suspect that I need to specify Header:=xlYes but I cannot figure out how?

VBA Code:
Sub Sort_Names_Main()

    Dim rAllData As Range

    With [Main]
        
        Set rAllData = .Range("Header_LastName").CurrentRegion
    
        With .Sort
            
            .SortFields.Clear
            .SortFields.Add Key:=Range("Header_LastName"), Order:=xlAscending
            .SortFields.Add Key:=Range("Header_FirstName"), Order:=xlAscending

            .SetRange rAllData
            .Apply
        
        End With '.Sort
        
    End With

End Sub
 

Excel Facts

Can a formula spear through sheets?
Use =SUM(January:December!E7) to sum E7 on all of the sheets from January through December
Typically it would be this way.

VBA Code:
        With .Sort
            .Header = xlYes
 
Upvote 0
Solution
rlv01. That's it! I would've taken a week to figure that out if at all. Thank you very much!
 
Upvote 0

Forum statistics

Threads
1,223,967
Messages
6,175,674
Members
452,666
Latest member
AllexDee

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