[英]Excel - VBA Macro - Stopping code at a specific sheet
我有許多具有相同模板的工作表,我想在其中對日期字段進行排序。 我一直在手動做,但我正在嘗試 VBA 為我做。 我有下面的代碼,但它適用於比我想要的更多的工作表。 我試圖弄清楚如何停止宏以在特定工作表處停止並在那里結束。
目標:從工作表 1-10 運行宏,停止@工作表 10 或如果工作表 = 工作表 11 然后停止。 我使用工作表 1-10、11 作為簡單的參考。 我會插入特定的工作表名稱。
我在網上找到了一些答案 -
If ws.Name <> "" Then
end with
但我不確定在下面的宏中在哪里輸入它。
Sub Macro1()
'
' sortbydate2 Macro
'
'
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
With ws
With .Sort
.SortFields.Clear
.SortFields.Add Key:=Range("A2:a49"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange ws.Cells
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
Next ws
End Sub
謝謝你,P1
您可以遍歷工作簿中的所有工作表並將過濾器應用於所有除 - 類似的內容:
For Each ws In ActiveWorkbook.Worksheets
if ws.Name <> "IDontWantFilters" Then
with ws
....
end with
end if
next ws
我認為這應該有效。 我假設一旦它到達 sheet11 你只想讓它完全停止
Sub Macro1()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
if ws.name = "Sheet11" then
exit sub
end if
With ws
With .Sort
.SortFields.Clear
.SortFields.Add Key:=Range("A2:a49"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange ws.Cells
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
Next ws
End Sub
IsError
與Application.Match
一起使用,以檢查是否在“異常數組”中找到了當前工作表的名稱。編碼
Option Explicit
Sub Macro1()
'
' sortbydate2 Macro
'
'
Dim Exceptions As Variant
Exceptions = Array("Sheet11", "Sheet12") ' add more or less.
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If IsError(Application.Match(ws.Name, Exceptions, 0)) Then
With ws
With .Sort
.SortFields.Clear
.SortFields.Add Key:=Range("A2:a49"), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
.SetRange ws.Cells
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
End If
Next ws
End Sub
如果你只想對前 10 個工作表進行排序,你可以做一個基本的循環來完成你的任務......
Dim ws As Worksheet
For i = 1 To 10
Set ws = Sheets(i)
With ws.Sort
.SortFields.Clear
.SortFields.Add Key:=Range("A2:A49"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
.SetRange Sheets(i).Cells
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next i
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.