简体   繁体   中英

How can I sort my my first two columns A-Z?

I'm trying to sort Columns that contain letters and numbers. I want to sort the Column AZ, I've tried reading up on some functions and attempting to get it to sort however I'm getting this error:

Private Function Sort2()
    Set HSheet = ThisWorkbook.Sheets("Building Parts")
    HBLR = HSheet.Range("A" & Rows.Count).End(xlUp).Row
    Worksheets("Building Parts").Activate

    With Range(Columns("A"), Columns("I"))
        .Sort key1:=Columns("A"), Order1:=xlDescending, Header:=xlNo
        .Sort key1:=Columns("B"), Order1:=xlDescending, Header:=xlNo
    End With
End Function

Mock Data:

在此处输入图片说明

Writing code from my comment as an answer so it is more readable


Using sort on individual columns across the same range will allow sorting xlAscending for each column, with the final sort providing the final AZ:

Mock Data:

Col 1      Col 2
A          1
A          3
B          1
C          1
A          2

If you want Col1 to have primary hierarchy, it is sorted last, so:

With Range(Columns(1), Columns(2))
    .Sort key1:=.Columns(2), order1:=xlAscending, Header:=xlYes
    .Sort key1:=.Columns(1), order1:=xlAscending, Header:=xlYes
End With

The above code is essentially:

.Range(.Columns(1), .Columns(2)).Sort key1:=.Columns(1), order1:=xlAscending, key2:=.Columns(2), order2:=xlAscending, Header:=xlYes

The single line approach has the highest priority as key1 , second highest as key2 , etc.


Output after code runs would be:

Col 1      Col 2
A          1
A          2
A          3
B          1
C          1

Edit (after accept):

I went back and added soem missing dot notation, found in the key1:=.Columns(1) ... unqualified references will lead to problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM