删除不具有特定文本的表格

时间:2015-10-30 11:36:31

标签: excel vba excel-vba

在Excel中,我需要删除所有不在(2)

中结束的工作表

以下代码正确地删除那些DO以(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

2 个答案:

答案 0 :(得分:1)

这里不行,你只需要否定完整的表达

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

答案 1 :(得分:0)

只是略微提示您当前的代码。将Application.DisplayAlerts移到循环外部。这些只需要在整个宏中关闭和打开一次,在这里您可以为每张纸打开它。这会增加代码中的迭代次数并使宏增长。

同样对于您的原始问题,如果工作表名称中存在(2),则运行if语句。要更改此设置,只需将Not放在if之后。

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

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