删除没有特定文字的表单

在Excel中,我需要删除所有不以(2)结尾的表单,

下面的代码正确地删除了那些以(2)结束的代码,我只是不确定如何反转这个,'不喜欢'似乎不工作

Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets If ws.Name Like "*" & "(2)" Then '~~> This check is required to ensure that you don't get an error '~~> if there is only one sheet left and it matches the delete criteria If ThisWorkbook.Sheets.Count = 1 Then MsgBox "There is only one sheet left and you cannot delete it" Else '~~> This is required to supress the dialog box which excel shows Application.DisplayAlerts = False ws.delete Application.DisplayAlerts = True End If End If Next 

只是对你当前的代码略有提示。 将Application.DisplayAlerts移动到循环之外。 这些只需要在整个macros中closures并打开一次,然后在每张纸上打开。 这会增加代码中的迭代次数,并增加macros。

如果(2)出现在工作表名称中,对于原始问题,您的if语句也会运行。 要改变这个简单的把Not放在if后面。

您也可以使用一个If语句再次减less代码。

 Dim ws As Worksheet Application.DisplayAlerts = False For Each ws In ThisWorkbook.Sheets If Not ws.Name Like "*" & "(2)" and ThisWorkbook.Sheets.Count > 1 Then ws.delete ElseIf ThisWorkbook.sheets.count = 1 then MsgBox "There is only one sheet left and you cannot delete it" Exit Sub End If Next ws Application.DisplayAlerts = True 

在这里不行,你只能否定完整的expression

 If Not ws.Name Like "*" & "(2)" Then