使用VBA进行多列排序

时间:2009-09-20 11:18:03

标签: excel vba sorting excel-vba

我正在使用VBA对Excel 2003中的列进行排序。我需要按列5升序排序,然后使用自定义顺序排序第3列,然后按列4升序排序。我很难搞定这种工作,但我并不完全理解OrderCustom的适用方式。

任何正确方向的指针都会受到赞赏:)我的代码如下。

With wsData
    lastrow = .Cells(Rows.Count, 1).End(xlUp).Row + 1
    lastCol = .Cells(4, Columns.Count).End(xlToLeft).Column

    Dim n As Long
    Application.AddCustomList ListArray:=Array("LOW", "MEDIUM OR HIGH", "HIGH ONLY")
    n = Application.GetCustomListNum(Array("LOW", "MEDIUM OR HIGH", "HIGH ONLY")) + 1

    Dim strSortOrder As String
    .Range(.Cells(1, 1), .Cells(lastrow, lastCol)).Sort _
        Key1:=.Range(.Cells(2, 5), .Cells(lastrow, lastCol)), Order1:=xlAscending, _
        Key2:=.Range(.Cells(2, 3), .Cells(lastrow, lastCol)), Order2:=xlDescending, _
        Key3:=.Range(.Cells(2, 4), .Cells(lastrow, lastCol)), Order3:=xlDescending, _
        OrderCustom:=n, _
        MatchCase:=False, Orientation:=xlSortColumns, Header:=xlYes
End With

1 个答案:

答案 0 :(得分:3)

尝试将您的排序分为3个单独的步骤,只有第二个步骤使用您的自定义排序顺序,即

.Range(.Cells(1, 1), .Cells(lastrow, lastCol)).Sort _
        Key1:=.Range(.Cells(2, 4), .Cells(lastrow, lastCol)), Order1:=xlDescending, _
        MatchCase:=False, Orientation:=xlSortColumns, Header:=xlYes

.Range(.Cells(1, 1), .Cells(lastrow, lastCol)).Sort _
        Key1:=.Range(.Cells(2, 3), .Cells(lastrow, lastCol)), Order1:=xlDescending, _
        OrderCustom:=n, _
        MatchCase:=False, Orientation:=xlSortColumns, Header:=xlYes

.Range(.Cells(1, 1), .Cells(lastrow, lastCol)).Sort _
        Key1:=.Range(.Cells(2, 5), .Cells(lastrow, lastCol)), Order1:=xlAscending, _
        MatchCase:=False, Orientation:=xlSortColumns, Header:=xlYes

请注意,与原始语句中的声明方式相比,我已经颠倒了执行这些排序的顺序。