下面的代码按设置范围内的数据排序
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?
答案 0 :(得分: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