Excel VBA对多行进行排序

时间:2016-08-02 14:58:34

标签: excel vba excel-vba sorting

我想按行升序排列A列到S列的每一行,共计5580行。向前,行数将增加。

我试图记录前2行的排序操作。然后我尝试合并代码以从第1行到第39行作为试验进行排序,但是失败了。

Sub Macro4()

Macro4 Macro

Rows("13:39").Select

ActiveWorkbook.Worksheets("Sheet1 (2)").Sort.SortFields.Clear

ActiveWorkbook.Worksheets("Sheet1 (2)").Sort.SortFields.Add Key:=Range( _
    "A13:S39"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal

With ActiveWorkbook.Worksheets("Sheet1 (2)").Sort
    .SetRange Range("A13:S" & Range("A" & Rows.Count).End(xlUp).Row)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlLeftToRight
    .SortMethod = xlPinYin
    .Apply

End With

Rows("14:14").Select
ActiveWorkbook.Worksheets("Sheet1 (2)").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1 (2)").Sort.SortFields.Add Key:=Range( _
    "A14:S14"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1 (2)").Sort
    .SetRange Range("A14:S14")
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlLeftToRight
    .SortMethod = xlPinYin
    .Apply
     End With
End Sub

1 个答案:

答案 0 :(得分:0)

这样的事情就是我想要的方式

For Each rw In Range("a1:E3").Rows

    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range(rw.Address), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange Range(rw.Address)
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlLeftToRight
        .SortMethod = xlPinYin
        .Apply
    End With

Next rw