To delete multiple sheets in Excel using VBA, you can use the Delete
method of the Sheets
object. Here’s an example:
Sub DeleteSheets()
Dim ws As Worksheet
' Define an array with the names of the sheets to be deleted
Dim sheetsToDelete() As Variant
sheetsToDelete = Array("Sheet2", "Sheet3", "Sheet4")
' Loop through each sheet name and delete the corresponding sheet
For Each sheetName In sheetsToDelete
On Error Resume Next ' Skip any error if the sheet doesn't exist
Set ws = Worksheets(sheetName)
If Not ws Is Nothing Then
Application.DisplayAlerts = False ' Disable the alert prompt
ws.Delete
Application.DisplayAlerts = True ' Enable alerts again
End If
On Error GoTo 0 ' Reset the error handling
Set ws = Nothing ' Release the object reference
Next sheetName
End Sub
In this example, we define an array sheetsToDelete
which contains the names of the sheets that we want to delete (e.g., “Sheet2”, “Sheet3”, “Sheet4”). We then loop through each sheet name and check if the sheet exists before deleting it. The On Error Resume Next
line is used to skip any error if the sheet doesn’t exist. After deleting the sheet, we reset the error handling (On Error GoTo 0
), release the object reference (Set ws = Nothing
), and move on to the next sheet name.
Make sure to replace the sheet names in the sheetsToDelete
array with your own desired sheet names.