如何使此录制的宏适用于工作簿中的所有工作表

时间:2017-07-06 17:57:46

标签: excel vba excel-vba

我有这个录制的宏适用于一张纸,但我复制并粘贴并更改了所有纸张名称,当我运行它时,它只适用于最后一张纸(甚至不是正确的纸张名称)。如何对工作簿的所有工作表进行排序(例如8)。

Sub Sort_Design_NEB()

    Range("A1").Select
 ActiveWorkbook.Worksheets("NEB_D").Sort.SortFields.Clear
 ActiveWorkbook.Worksheets("NEB_D").Sort.SortFields.Add Key:= _
    Range("E2:E55"), SortOn:=xlSortOnValues, Order:=xlAscending,      DataOption:= _
    xlSortNormal
ActiveWorkbook.Worksheets("NEB_D").Sort.SortFields.Add Key:= _
    Range("H2:H55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
ActiveWorkbook.Worksheets("NEB_D").Sort.SortFields.Add Key:= _
    Range("G2:G55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
With ActiveWorkbook.Worksheets("NEB_D").Sort
    .SetRange Range("A1:H55")
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

End Sub

1 个答案:

答案 0 :(得分:1)

尝试使用工作簿的所有工作表的循环。像这样:

Dim WS_Count As Integer
     Dim I As Integer

     ' Set WS_Count equal to the number of worksheets in the active
     ' workbook.
     WS_Count = ActiveWorkbook.Worksheets.Count

     ' Begin the loop.
     For I = 1 To WS_Count
         Range("A1").Select
         With ActiveWorkbook.Worksheets(I)
             .Sort.SortFields.Clear
             .Sort.SortFields.Add Key:= _
             .Range("E2:E55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
             xlSortNormal
             .Sort.SortFields.Add Key:= _
             .Range("H2:H55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
             xlSortNormal
         .Sort.SortFields.Add Key:= _
             .Range("G2:G55"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
             xlSortNormal
         End With
         With ActiveWorkbook.Worksheets(I).Sort
             .SetRange Range("A1:H55")
             .Header = xlYes
             .MatchCase = False
             .Orientation = xlTopToBottom
             .SortMethod = xlPinYin
             .Apply
         End With
Next I

使用声明更新。感谢Thomas Inzina。