我假设您要排序的五列是 A 到 E。这个宏循环遍历每一列(整列)并独立于相邻列进行排序。
尝试这个:
Sub Macro2()
Set rng = Range("A:E")
For Each col In rng.Columns
Set rng = Columns(col.Column)
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Cells(1, col.Column), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange rng
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next
End Sub
数据看起来像这样开始:
运行宏后将如下所示:
请注意,最后一列未触及。
****编辑****
这是您如何从左到右排序行而不是如上所示的列:(它将行 A1 到 A10 从列“A”排序到列“E”
Sub Macro2()
Set Rng = Range("A1:E10")
col = Rng.Cells(Rng.Count).Column
Dim lastcol As Integer
lastcol = Rng.Cells(Rng.Count).Column
For Each rrow In Rng.Rows
Set RngB = Range(ActiveSheet.Cells(rrow.Row, Rng.Column), ActiveSheet.Cells(rrow.Row, lastcol))
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=RngB, _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange RngB
.Header = xlNo
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
Next
End Sub