Excel使用代码删除除活动工作表和指定工作表之外的所有工作表

时间:2017-01-19 15:52:41

标签: excel excel-vba vba

使用其CodeNames删除活动工作簿中除选定/活动工作表和4个指定工作表之外的所有工作表的最佳方法是什么?

我已经提出了这个代码并且它有效,但似乎有更好的方法来实现它:

Sub delete_test()


Application.ScreenUpdating = False
Application.DisplayAlerts = False

'Deletes all sheets except ActiveSheet and specified sheets using codenames
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets
Select Case ws.CodeName
Case "Sheet1", "Sheet2", "Sheet3", "Sheet4"
        Case Else
    With ws

If ws.NAme <> ThisWorkbook.ActiveSheet.NAme Then
ws.Delete
End If

    End With
End Select
Next


End Sub

2 个答案:

答案 0 :(得分:3)

您的代码已经相当简洁。

您可以将ThisWorkbook.ActiveSheet.Name添加到第一个案例中,并避免使用IF。

也不需要With Block,因为你只做一件事。额外的打字不仅仅是指单。

确保重新打开提醒。

Sub delete_test()


Application.ScreenUpdating = False
Application.DisplayAlerts = False

'Deletes all sheets except ActiveSheet and specified sheets using codenames
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets
    Select Case ws.CodeName
        Case "Sheet1", "Sheet2", "Sheet3", "Sheet4", ThisWorkbook.ActiveSheet.CodeName
        Case Else
            ws.Delete
    End Select
Next

Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

答案 1 :(得分:2)

您可以检查ws是否为Not ActiveSheet,然后检查CodeName是否不符合您的标准。

Sub delete_test()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

'Deletes all sheets except ActiveSheet and specified sheets using codenames
Dim ws As Worksheet

For Each ws In ThisWorkbook.Sheets
    If Not Worksheets(ws.Name) Is ActiveSheet Then '<-- first check if sheet is not active sheet
        Select Case ws.CodeName
            Case "Sheet1", "Sheet2", "Sheet3", "Sheet4"

            Case Else
                ws.Delete
        End Select
    End If
Next ws 

End Sub