VBA Excel sort range by specific column VBA Excel sort range by specific column vba vba

VBA Excel sort range by specific column


Try this code:

Dim lastrow As Longlastrow = Cells(Rows.Count, 2).End(xlUp).RowRange("A3:D" & lastrow).Sort key1:=Range("B3:B" & lastrow), _   order1:=xlAscending, Header:=xlNo


Or this:

Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _    Order1:=xlAscending, Header:=xlYes


If the starting cell of the range and of the key is static, the solution can be very simple:

Range("A3").SelectRange(Selection, Selection.End(xlToRight)).SelectRange(Selection, Selection.End(xlDown)).SelectSelection.Sort key1:=Range("B3", Range("B3").End(xlDown)), _order1:=xlAscending, Header:=xlNo