【问题标题】:Dynamic nested sorts using Excel VBA使用 Excel VBA 进行动态嵌套排序
【发布时间】:2018-01-18 00:07:37
【问题描述】:

我去过MSDN page 了解如何使用多个排序字段进行排序。它基本上说给你的键编号并将它们设置为等于排序字段。

我想遍历一个 N 大小的整数数组,以按数组中的值对范围进行排序。例如,如果我的工作表有 100 列数据,我可能想根据第 3,18 和 62 列进行排序;所以 N 是 3。问题是我无法命名排序键 "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

你有什么推荐的?

【问题讨论】:

  • @TimWilliams 添加。我为几个变量使用了通用名称,但我认为这很清楚。基本上,在遍历数组中的每个值之后,我会应用排序字段。
  • 当你运行它时会发生什么?
  • 没有错误信息,但它没有排序。我寻找使用即时窗口确定应用排序字段的方法,但空手而归。

标签: vba excel sorting range


【解决方案1】:

尝试类似:

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

【讨论】:

  • 我没有意识到我必须在我的引用范围内重新引用工作表。谢谢。
猜你喜欢
  • 1970-01-01
  • 2023-02-10
  • 2019-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多