按特定列号排序 - Excel VBA

BD528

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

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?

院长

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章