In VBA, How to sort a range of cells.

Post Reply
wwj
Posts: 2497
Joined: 27 Jan 2007 08:16

In VBA, How to sort a range of cells.

Post by wwj »

In VBA, How to sort a range of cells.
- Verified!

Code: Select all



Sub sub_sort_by_Residuals(tabName As String)
'
' Macro for sorting without Select/Activate
'
    Dim wsDest As Worksheet
'
    ' Set target sheet
    Set wsDest = ThisWorkbook.Sheets(tabName)
    
    ' Clear existing sort fields
    wsDest.Sort.SortFields.Clear
    
    ' Add sort key (column H, rows 3–326)
    wsDest.Sort.SortFields.Add2 _
        Key:=wsDest.Range("H3:H326"), _
        SortOn:=xlSortOnValues, _
        Order:=xlDescending, _
        DataOption:=xlSortNormal
        
    ' Apply sort to range B2–O326
    With wsDest.Sort
        .SetRange wsDest.Range("B2:O326")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
        
    ' Optional: put the cursor on Q2 (must activate sheet if you want it visible)
    wsDest.Activate
    wsDest.Range("Q2").Select
    
End Sub


Post Reply