2017-07-06 54 views
0

我有這個錄製的宏適用於一張工作表,但我複製並粘貼並更改了所有工作表名稱,當我運行它時,它僅適用於最後一張工作表甚至沒有正確的表名)。我如何排列工作簿的所有表單(有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 

結束子

回答

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。

+2

您需要限定所有範圍參考。 'Range(「E2:E55」)'應該像這樣'ActiveWorkbook.Worksheets(I).Range(「E2:E55」)'限定。我會使用'With ActiveWorkbook.Worksheets(I)'來減少混亂。 – 2017-07-06 18:14:36

+0

這適用於按範圍G對列進行排序,但不適用於範圍E – samred

+0

@Thomas - 將嘗試此 – samred

相關問題