使用Excel VBA进行动态嵌套排序

时间:2017-08-09 22:59:41

标签: excel vba excel-vba sorting range

我去过这个MSDN page来了解有关多个排序字段的排序。它基本上表示对键进行编号并将它们设置为等于排序字段。

我想循环遍历N大小的整数数组,以按数组中的值对范围进行排序。例如,如果我的工作表有100列数据,我可能想要根据第3,18和62列进行排序;所以N将是3.问题是我无法将排序键"key" & i命名为i从1循环到N.

到目前为止我所拥有的:

 With Worksheets("SalesRep").Sort
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    for i=1 to myArrayLength
       SortFields.Add Key:=Range(cells(1,colNumArray(i)).address,cells(lastRow,colNumArray(i)).address)
    next i
    .Apply
End With

你推荐什么?

1 个答案:

答案 0 :(得分:2)

尝试类似:

Dim sht As WorkSheet

Set sht = .Worksheets("SalesRep")

With sht.Sort
    .SortFields.Clear  '<<<<< clear any previous
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    for i=1 to myArrayLength
       SortFields.Add Key:=sht.Range(sht.cells(1,colNumArray(i)), _
                                     sht.cells(lastRow,colNumArray(i)))

       'maybe cleaner as
       'SortFields.Add Key:=sht.Cells(1, colNumArray(i)).Resize(lastRow, 1)
    next i
    .Apply
End With

您不需要范围参考中的.Address,但您需要添加工作表限定符,否则当其他工作表处于活动状态时,您的代码将失败。