使用Excel VBA进行dynamic嵌套sorting

我去过这个MSDN页面了解有关sorting多个sorting字段。 它基本上说是给你的密钥编号,并把它们设置成等于sorting字段。

我想通过一个N大小的整数数组来循环排列数组中的值。 例如,如果我的工作表有100列的数据,我可能想根据列3,18和62进行sorting; 所以N会是3.问题是我无法命名sorting键"key" & 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 

你有什么build议?

尝试像这样:

 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 ,但您需要添加工作表限定符,否则当任何其他工作表处于活动状态时,代码将失败。