【问题标题】:Multi-column sort with VBA使用 VBA 进行多列排序
【发布时间】:2010-11-29 20:45:34
【问题描述】:

我在 Excel 2003 中使用 VBA 对列进行排序。我需要按第 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

【问题讨论】:

    标签: vba sorting excel


    【解决方案1】:

    尝试将您的排序分成 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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-05
      相关资源
      最近更新 更多