5

How can I sort on multiple columns (keys/orders) at the same time? When I run my below code it re-sorts the data when executing each line instead of one sort with multiple columns in the sort. Changing the 'key' or 'order' number from 1 to 2, etc. does not help. Thanks.

wsLast_Row = Cells(Rows.Count, 2).End(xlUp).Row
Range("A3:BZ" & wsLast_Row).Sort key1:=Range("A3:A" & wsLast_Row), _
   order1:=xlAscending, Header:=xlNo
Range("A3:BZ" & wsLast_Row).Sort key1:=Range("B3:B" & wsLast_Row), _
   order1:=xlAscending, Header:=xlNo
Range("A3:BZ" & wsLast_Row).Sort key1:=Range("C3:C" & wsLast_Row), _
   order1:=xlAscending, Header:=xlNo
Range("A3:BZ" & wsLast_Row).Sort key1:=Range("D3:D" & wsLast_Row), _
   order1:=xlAscending, Header:=xlNo
Range("A3:BZ" & wsLast_Row).Sort key1:=Range("F3:F" & wsLast_Row), _
   order1:=xlAscending, Header:=xlNo
0

1 Answer 1

8
Sub sdad()
    wsLast_Row = Cells(Rows.Count, 2).End(xlUp).Row
    With ActiveWorkbook.ActiveSheet.Sort
        .SortFields.Clear
        .SortFields.Add Key:=Range("A3:A" & wsLast_Row), Order:=xlAscending
        .SortFields.Add Key:=Range("B3:B" & wsLast_Row), Order:=xlAscending
        .SortFields.Add Key:=Range("C3:C" & wsLast_Row), Order:=xlAscending
        .SortFields.Add Key:=Range("D3:D" & wsLast_Row), Order:=xlAscending
        .SetRange Range("A3:BZ" & wsLast_Row)
        .Header = xlNo
        .Apply
    End With
End Sub
Sign up to request clarification or add additional context in comments.

4 Comments

I copied your code into my sub and received an error box reading 'Compile error: Named argument not found' 'key4:=' is highlighted.
Never knew that VBA was limited to 3 keys. See revised answer
Works perfectly as intended, ty @Abe Gold
I ran into the 3-key limitation today and this worked a treat. Thank you Abe Gold!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.