如何删除 VBA 中某些工作表以外的工作表

How to delete sheets except for certain sheets in the VBA

我有这段代码,但是当我 运行 它时 excel 总是崩溃。我没有收到错误代码或任何东西。 Excel 刚刚结束。

Sub DeleteSheets()
    Dim xWs As Worksheet
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    For Each xWs In Application.ActiveWorkbook.Worksheets
        If xWs.Name <> "Overview" And xWs.Name <> "Models-Features" And xWs.Name <> "Formulas" And xWs.Name <> "Original Features" Then
            xWs.Delete
        End If
    Next
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

您的代码似乎正在删除导致错误的所有 sheet,即使其中一个被标记为“概述”。我使用 Select 清理了它,现在不会删除适当的命名 sheets:

Sub DeleteSheets()
    Dim xWs As Worksheet
    Application.EnableEvents = False
    Application.Calculation = xlManual
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    For Each xWs In Application.ActiveWorkbook.Worksheets
        If Sheets.Count = 1 Then Exit For
        Select Case xWs.Name
            Case "Overview"
            Case "Models-Features"
            Case "Formulas"
            Case "Original Features"
            Case Else
                xWs.Delete
        End Select
    Next
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlAutomatic
End Sub

Edit1:添加了对 Sheets.Count 的检查,这将防止因删除工作簿中的最后一个 sheet 而导致的错误。

Edit2:添加了额外的 application 限制条件