我试图在使用"""的工作簿中删除所有工作表,但有三个工作表。进入"如果......然后"但是声明正在删除其中一个。我写的是以下内容:
Sub delete()
For Each Sheet In Application.Worksheets
Application.DisplayAlerts = False
If (Sheet.Name <> "Close Price" And Sheet.Name <> "Parameters" And Sheet.Name <> "Stock") Then
Sheet.delete
End If
Next Sheet
Application.DisplayAlerts = True
End Sub
我也尝试了以下内容:
Sub delete()
For Each Sheet In Application.Worksheets
Application.DisplayAlerts = False
If (Sheet.Name <> "Close Price" And Sheet.Name <> "Parameters") Then
If (Sheet.Name <> "Stock") Then
Sheet.delete
End If
End If
Next Sheet
Application.DisplayAlerts = True
End Sub
但也没有工作。它尊重&#34;关闭价格&#34;和&#34;参数&#34;工作表但不是&#34; Stock&#34;工作表。
你知道我怎么解决它?。
非常感谢并且一切顺利。 grd_aa
答案 0 :(得分:1)
可以使用工作表名称数组立即删除工作表。在For-Each
循环中,将要删除的工作表名称收集到一个数组中。然后只需调用Worksheets(sheetsToDeteleArrayHere).delete
,即可立即删除数组中的所有工作表。 HTH
注意:使用Trim(工作表名称)可以确保前导和/或结束空格不是比较的一部分。)
Sub delete()
Dim sheet
Dim sheetsToDetele
Application.DisplayAlerts = False
For Each sheet In Application.Worksheets
If Trim(sheet.name) = "Close Price" Then GoTo continue
If Trim(sheet.name) = "Parameters" Then GoTo continue
If Trim(sheet.name) = "Stock" Then GoTo continue
If IsArray(sheetsToDetele) Then
ReDim Preserve sheetsToDetele(1 To UBound(sheetsToDetele) + 1)
Else
ReDim sheetsToDetele(1 To 1)
End If
sheetsToDetele(UBound(sheetsToDetele)) = sheet.name
continue:
Next sheet
If Not IsArray(sheetsToDetele) Then _
Exit Sub
Application.Worksheets(sheetsToDetele).delete
Application.DisplayAlerts = True
End Sub
答案 1 :(得分:1)
正如您所说的if语句不尊重第三个and
,我会将其更改为Select Case
,因为只有在名称与列出的其他名称不匹配时才删除在案件陈述中
(我知道我可以将所有名字放在一行
Case "Close Price", "Parameters", "Stock"
我认为这样看起来更整洁:)
Sub delete()
Application.DisplayAlerts = False
For Each Sheet In Application.Worksheets
Select Case Sheet.Name
Case "Close Price"
Case "Parameters"
Case "Stock"
Case Else
Sheet.delete
End Select
Next Sheet
Application.DisplayAlerts = True
End Sub
答案 2 :(得分:0)
问题是当您删除sheet
时,您正在将枚举更改为循环无法继续的点,因为完整性已被破坏。
相反,当您需要执行此操作时,请使用基于索引的循环,然后向后。这样,当您删除工作表时,下一次迭代不会受到影响。
Sub delete()
Application.DisplayAlerts = False
Dim i As Integer
' Work backwards so if/when a sheet is deleted,
' the indexes are not changed
For i = Sheets.Count To 1 Step -1
If Sheets(i).Name <> "Close Price" _
And Sheets(i).Name <> "Parameters" _
And Sheets(i).Name <> "Stock" _
Then
Sheets(i).Delete
End If
Next
Application.DisplayAlerts = True
End Sub