Brianna Cates
Brianna Cates

Reputation: 347

If statement to delete tab if there but move on if page is not there

I have a code that deletes a tab in the worksheet then runs another code. I am currently running into an issue that if the sheet is not there the code gives me an error... I'm wondering if I could make an if statement that looks if the tab is there and if not it moves on and if it is there it will delete it. I have the code that I have written already posted below but I have no idea how to do the if in the delete section.

Thanks!

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

Application.DisplayAlerts = False

ws.delete

Call Sorting

End Sub

Upvotes: 0

Views: 97

Answers (2)

Darren Bartrup-Cook
Darren Bartrup-Cook

Reputation: 19737

Check if the sheet exists first:

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

Upvotes: 1

Try this

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

Upvotes: 0

Related Questions