我正在编写一个程序来删除所有带有月份名称的工作表。但是,在程序删除工作表后,它会给我一个自动化错误
Sub DelSheet()
Dim i As Integer
Dim months() As String
months() = Split("January February March April May June July Auguest September October November December")
Dim ws As Worksheet
Application.DisplayAlerts = False
For Each ws In Worksheets
For i = 0 To UBound(months)
If ws.Name = months(i) Then
ws.Delete
End If
Next i
Next ws
Application.DisplayAlerts = True
End Sub
在我删除工作表之后,当它开始下一个循环时,Collection(工作表)中的元素已经改变了。
对于工作表中的每个ws
我失去了
答案 0 :(得分:1)
是 - 循环收集 您可能想要删除项目,最好向后工作:
Sub DelSheet()
Dim i As Integer, n As Long, w as Long
Dim months() As String
months() = Split("January February March April May June July Auguest September October November December")
Dim ws As Worksheet
Application.DisplayAlerts = False
n = Worksheets.Count
For w = n to 1 Step - 1
Set ws = Worksheets(w)
For i = 0 To UBound(months)
If ws.Name = months(i) Then
ws.Delete
Exit For
End If
Next i
Next w
Application.DisplayAlerts = True
End Sub
答案 1 :(得分:1)
您好,这是另一种解决方案。在这种情况下,我们只使用一个循环
Sub DelSheet()
Const strMONTHS As String = "January February March April May June July Auguest September October November December"
Dim sh As Worksheet
Dim arrSheetsToDelete() As String
Dim i As Long
' Loop through the sheets and create the array
For Each sh In ThisWorkbook.Sheets
If Not InStr(1, strMONTHS, sh.Name) = 0 Then
ReDim Preserve arrSheetsToDelete(i)
arrSheetsToDelete(i) = sh.Name
i = i + 1
End If
Next sh
'Delete the array of sheets
Application.DisplayAlerts = False
ThisWorkbook.Sheets(arrSheetsToDelete).Delete
Application.DisplayAlerts = True
End Sub
希望这会有所帮助:)