简体   繁体   中英

Sorting by 2 keys… first by column f and then by g… Whole range of the worksheet is A2:S

somehow I don't get the sortkey stuff. I've looked through some examples on the web. They seem pretty clear but I don't understand how you exactly assign a key to a certain column... My code should sort all from A2:S. The first criteria is column F and then sort by column G. Example:

F2: A    G2:B
F3: A    G3:C
F4: A    G4:A

Should become:

F2: A    G2:A
F3: A    G3:B
F4: A    G4:C

Code I've got until now:

Private Sub ButtonExport_Click()

    Dim sKey1 As String
    Dim sKey2 As String
    Dim sKey3 As String

    sKey1 = Worksheets("Variable Tags").Range("lblSortByKey1").Value
    sKey2 = Worksheets("Variable Tags").Range("lblSortByKey2").Value

    If sKey2 = "" Then
        Call SortTable(sKey1, , , "tblTagLists_All")
        MsgBox "Sorting done based on one column"
    Else
        Call SortTable(sKey1, sKey2, , "tblTagLists_All")
        MsgBox "Sorting done based on two columns"
    End If

End Sub

Try to record Macro and then organize the code.

Sub NinjaSort()
    Dim theRange As Range

    Set theRange = Range("F1:G6")

    With ActiveSheet
        .Sort.SortFields.Clear
        .Sort.SortFields.Add Key:=theRange.Columns(1).Cells, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        .Sort.SortFields.Add Key:=theRange.Columns(2).Cells, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With .Sort
            .SetRange theRange
            .Header = xlYes
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End With
End Sub

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