【问题标题】:Sorting by specific column number - Excel VBA按特定列号排序 - Excel VBA
【发布时间】:2019-07-16 17:47:13
【问题描述】:

下面的代码按设定范围内的数据排序

lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
lastcol = .Cells(1, Columns.Count).End(xlToLeft).Column 

mySheet.Sort.SortFields.Clear
mySheet.Sort.SortFields.Add Key:=Range("A2:A" & lastrow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With mySheet.Sort
    .SetRange Range("A1:U" & lastrow)
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

每次执行代码时,列数可能会有所不同。有没有办法调整这段代码,使范围同时使用 lastrow 和 lastcol?

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    是的,请参见下面的调整(未测试),但您应该了解逻辑。

    With mySheet.Sort
        .SetRange Range(mySheet.Cells(1,1), mySheet.Cells(lastrow,lastcol))
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    

    【讨论】:

      猜你喜欢
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多