如果语句删除选项卡,如果有,但如果页面不存在则继续

时间:2016-03-03 17:05:15

标签: vba excel-vba excel

我有一个代码删除工作表中的选项卡,然后运行另一个代码。我目前遇到一个问题,如果表格不存在,代码会给我一个错误...我想知道我是否可以制作一个if语句,看看该标签是否在那里,如果没有它继续前进,如果它它会删除它吗?我已经在下面发布了我编写的代码,但我不知道如何在删除部分中执行if。

谢谢!

Sub delete()
Dim ws As Worksheet
Set ws = Worksheets("Workbench Report")

Application.DisplayAlerts = False

ws.delete

Call Sorting

End Sub

2 个答案:

答案 0 :(得分:1)

检查工作表是否首先存在:

Sub delete()
    Dim ws As Worksheet

    If WorksheetExists("Workbench Report") Then

        Set ws = Worksheets("Workbench Report")

        Application.DisplayAlerts = False

        ws.delete

        Call Sorting

    End If

End Sub

    Public Function WorkSheetExists(SheetName As String, Optional WrkBk As Workbook) As Boolean
        Dim wrkSht As Worksheet

        If WrkBk Is Nothing Then
            Set WrkBk = ThisWorkbook
        End If

        On Error Resume Next
            Set wrkSht = WrkBk.Worksheets(SheetName)
            WorkSheetExists = (Err.Number = 0)
            Set wrkSht = Nothing
        On Error GoTo 0
    End Function

答案 1 :(得分:0)

试试这个

Sub delete()
Dim i As Integer

i = 1

Application.DisplayAlerts = False

While i <= ActiveWorkbook.Worksheets.Count

Sheets(i).Select

If ActiveSheet.Name = "Workbench Report" Then

ActiveSheet.delete

End If

i = i + 1

Wend

Call Sorting

Application.DisplayAlerts = True

End Sub