有没有办法让一个人使用以下示例模拟Excel中的Sort命令?
我有60行和53列数据。在使用sort命令后,我确实能够得到我想要的结果但是相信如果我能有一个宏,它会节省我这么多时间。您可以看到之前和之后的图像,以便了解我一直在努力实现的目标。
[]
[]
e.g。
SORT LEFT TO RIGHT
SORT BY [ROW 2] | SORT ON [VALUES] | ORDER [SMALLEST TO LARGEST]
SORT BY [ROW 3] | SORT ON [VALUES] | ORDER [SMALLEST TO LARGEST]
...
...
SORT BY [ROW 59] | SORT ON [VALUES] | ORDER [SMALLEST TO LARGEST]
SORT BY [ROW 60] | SORT ON [VALUES] | ORDER [SMALLEST TO LARGEST]
更新:我运行宏录制器以查看它的外观,这是从第2行到第61行的缩短代码。
Sub Macro3()
ActiveWorkbook.Worksheets("Sheet11").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet11").Sort.SortFields.Add Key:=Range("B2:BB2") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet11").Sort.SortFields.Add Key:=Range("B3:BB3") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet11").Sort.SortFields.Add Key:=Range("B4:BB4") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet11").Sort.SortFields.Add Key:=Range("B5:BB5") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
...MORE ROWS HERE IN THE PATTERN AS SHOWN
...MORE ROWS HERE IN THE PATTERN AS SHOWN
ActiveWorkbook.Worksheets("Sheet11").Sort.SortFields.Add Key:=Range("B57:BB57" _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet11").Sort.SortFields.Add Key:=Range("B58:BB58" _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet11").Sort.SortFields.Add Key:=Range("B59:BB59" _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet11").Sort.SortFields.Add Key:=Range("B60:BB60" _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet11").Sort.SortFields.Add Key:=Range("B61:BB61" _
), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet11").Sort
.SetRange Range("B1:BB63")
.Header = xlYes
.MatchCase = False
.Orientation = xlLeftToRight
.SortMethod = xlPinYin
.Apply
End With
End Sub
有没有让这更简洁?
答案 0 :(得分:4)
您可以直接在Excel中按行排序,不需要VBA:
Data->Sort->Options...->Sort left to right
我想从vba中排序,将Rows指定为条件字段:
Sub SortByRows()
With ActiveSheet.UsedRange
.Sort Key1:=.Rows(1), Key2:=.Rows(2), Key3:=.Rows(3)
End With
End Sub
但是,您的标准数量有限。由于您需要更多标准字段,因此更为棘手:
Sub SortByRows()
With ActiveSheet
Set target = .Range(.Cells(2, 2), .Cells(.UsedRange.Rows.Count, .UsedRange.Columns.Count))
End With
With ActiveSheet.Sort
.SortFields.Clear
.SetRange target
.Orientation = xlLeftToRight
.Header = xlNo
For Each r In target.Rows
.SortFields.Add r
Next
.Apply
End With
End Sub