使用VBA在Excel中删除工作表

时间:2015-07-17 11:59:56

标签: excel vba excel-vba

我有一个生成许多工作簿的宏。我希望宏在运行开始时检查文件是否包含2个电子表格,如果它们存在则删除它们。

我试过的代码是:

If Sheet.Name = "ID Sheet" Then
    Application.DisplayAlerts = False
    Sheet.Delete
    Application.DisplayAlerts = True

End If

If Sheet.Name = "Summary" Then
    Application.DisplayAlerts = False
    Sheet.Delete
    Application.DisplayAlerts = True
End If

此代码返回错误:

  

运行时错误#424,需要对象。

我可能有错误的格式,但如果有更简单的方法,那将非常有用。

5 个答案:

答案 0 :(得分:34)

考虑:

Sub SheetKiller()
    Dim s As Worksheet, t As String
    Dim i As Long, K As Long
    K = Sheets.Count

    For i = K To 1 Step -1
        t = Sheets(i).Name
        If t = "ID Sheet" Or t = "Summary" Then
            Application.DisplayAlerts = False
                Sheets(i).Delete
            Application.DisplayAlerts = True
        End If
    Next i
End Sub

注:

因为我们正在删除,所以我们向后运行循环

答案 1 :(得分:9)

试试这段代码:

For Each aSheet In Worksheets

    Select Case aSheet.Name

        Case "ID Sheet", "Summary"
            Application.DisplayAlerts = False
            aSheet.Delete
            Application.DisplayAlerts = True

    End Select

Next aSheet

答案 2 :(得分:4)

您可以使用On Error Resume Next,然后无需遍历工作簿中的所有工作表。

注意:当工作簿仅包含这两张工作表时,只会删除第一张工作表。

Dim book
Dim sht as Worksheet

set book= Workbooks("SomeBook.xlsx")

On Error Resume Next

Application.DisplayAlerts=False 

Set sht = book.Worksheets("ID Sheet")
sht.Delete

Set sht = book.Worksheets("Summary")
sht.Delete

Application.DisplayAlerts=True 

On Error GoTo 0

答案 3 :(得分:0)

Worksheets("Sheet1").Delete
Worksheets("Sheet2").Delete

答案 4 :(得分:-1)

在你的if语句中尝试:

Application.DisplayAlerts = False
Worksheets(“Sheetname”).Delete
Application.DisplayAlerts = True