Sorting range in Excel with VBA


Sorte custom range in Excel by one or more columns

11.05.2021, Goran Dolenc
Categories: Excel VBA
Tags: VBA


Dim shtSearch As Worksheet
Dim lngFirstRow As Long
Dim lngLastRow As Long
Dim rngInput As Range

Set shtSearch = ThisWorkbook.Sheets("Search")

With shtSearch

lngFirstRow = 5
lngLastRow = .Cells(.Rows.Count, "U").End(xlUp).Row

' sort by keywords
Set rngInput = Range(.Cells(lngFirstRow, .Columns("U").Column), .Cells(lngLastRow, .Columns("AI").Column))
'rngInput.Sort Key1:=Range("AA5"), Order1:=xlAscending, Header:=xlYes
With .Sort
.SetRange rngInput ' range to sort
.SortFields.Add Key:=Range("AA5"), Order:=xlAscending ' first sort criteria
'.SortFields.Add Key:=Range("AB5"), Order:=xlAscending ' second sort criteria
.Header = xlYes
End With

    End With