0

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
Community
  • 1
  • 1
Brianna Cates
  • 337
  • 1
  • 7
  • 22

2 Answers2

1

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
Darren Bartrup-Cook
  • 18,362
  • 1
  • 23
  • 45
  • 2
    please by mindful that this question has already been asked and well-answered on SO [here](http://stackoverflow.com/questions/6688131/test-or-check-if-sheet-exists) – Scott Holtzman Mar 03 '16 at 17:22
0

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
  • 2
    please by mindful that this question has already been asked and well-answered on SO [here](http://stackoverflow.com/questions/6688131/test-or-check-if-sheet-exists) – Scott Holtzman Mar 03 '16 at 17:22