按2键排序...首先按列f然后按g ...工作表的整个范围是A2:S

时间:2013-10-28 13:43:57

标签: excel vba sorting

不知怎的,我没有得到sortkey的东西。我在网上看了一些例子。它们看起来很清楚,但我不明白你是如何为某个列完全分配一个键...我的代码应该从A2:S中排序。第一个标准是F列,然后按G列排序。 例如:

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

应该成为:

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

我到现在为止的代码:

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

1 个答案:

答案 0 :(得分:1)

尝试录制宏,然后组织代码。

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