excel vba delete worksheet if exists

Code to Delete Worksheet in Excel VBA if it Exists

Sub DeleteSheetIfExists(sheetName As String)
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = sheetName Then
            Application.DisplayAlerts = False
            ws.Delete
            Application.DisplayAlerts = True
            Exit For
        End If
    Next ws
End Sub

Explanation:

1. Sub DeleteSheetIfExists(sheetName As String): This line defines a VBA subroutine named DeleteSheetIfExists, which takes a parameter sheetName of type String.

2. Dim ws As Worksheet: This line declares a variable ws of type Worksheet.

3. For Each ws In ThisWorkbook.Worksheets: This is a For Each loop that iterates through each worksheet in the current workbook.

4. If ws.Name = sheetName Then: This line checks if the name of the current worksheet matches the specified sheetName.

5. Application.DisplayAlerts = False: This line turns off the display of alerts to prevent the user from being prompted when deleting the worksheet.

6. ws.Delete: If a matching worksheet is found, this line deletes the worksheet.

7. Application.DisplayAlerts = True: This line turns the display of alerts back on after the worksheet is deleted.

8. Exit For: This line exits the For Each loop once a matching worksheet has been deleted.