Excel VBA - 多级排序

问题描述 投票:0回答:1

如何更改以下代码以多级方式排序?目前,代码一次对表进行一次排序,我想将它作为多级排序一起排序。

以下是我想要实现的目标:

enter image description here

这是我的代码,它一次对表格进行一次排序:

Range("A4:L" & lastRow).Sort key1:=Range("A4:A" & lastRow), _
    order1:=xlAscending, Header:=xlNo
Range("A4:L" & lastRow).Sort key1:=Range("B4:B" & lastRow), _
    order1:=xlAscending, Header:=xlNo
Range("A4:L" & lastRow).Sort key1:=Range("C4:C" & lastRow), _
    order1:=xlAscending, Header:=xlNo
Range("A4:L" & lastRow).Sort key1:=Range("D4:D" & lastRow), _
    order1:=xlAscending, Header:=xlNo
Range("A4:L" & lastRow).Sort key1:=Range("E4:E" & lastRow), _
    order1:=xlAscending, Header:=xlNo

如何更改以上内容以将所有内容排序?

excel excel-vba sorting vba
1个回答
3
投票

我总是建议摆脱录制的.Sort方法,而不是'只需要你的'VBA排序代码。但是,存在一个问题,即每种类型最多只能排序三个排序键;解决方案是执行两个排序操作。先排序最高的序数,然后排序最后三个主要排序序数。

With Worksheets("Sheet1").Range("A4:L" & lastRow)
    .Cells.Sort Key1:=.Columns("D"), Order1:=xlAscending, _
                Key2:=.Columns("E"), Order2:=xlAscending, _
                Orientation:=xlTopToBottom, Header:=xlYes
    .Cells.Sort Key1:=.Columns("A"), Order1:=xlAscending, _
                Key2:=.Columns("B"), Order2:=xlAscending, _
                Key3:=.Columns("C"), Order3:=xlAscending, _
                Orientation:=xlTopToBottom, Header:=xlYes
End With

你已经将单元格地址与hte图像中的表格列或标题标签混合在一起,所以我不确定我是否得到了正确的序数。以上将按列A作为主要,B作为次要,C作为第三,D作为第四,E作为第五。

© www.soinside.com 2019 - 2024. All rights reserved.