Finance

Charts

Statistics

Macros

Search

Deleting Worksheets With Excel VBA

The following VBA procedure deletes two worksheets from the current workbook:

Sub DeleteSheets()
    ThisWorkbook.Activate
    Worksheets("New").Delete
    Worksheets("Sheet1_Copy").Delete
End Sub

Explanation:

  1. Ensure the correct workbook is active
  1. Activate

This guarantees that the macro operates within the workbook containing the code, especially important when multiple workbooks are open.

Delete worksheets by name

Worksheets(« New »).Delete

Worksheets(« Sheet1_Copy »).Delete

    • The Delete method is used to permanently remove the worksheets named « New » and « Sheet1_Copy ».
    • Both sheets are accessed by their exact names.
    • Once deleted, these sheets and their contents cannot be recovered unless the workbook is closed without saving or the action is undone.

⚠️ Important Warning (Excel 2016 and newer):

  • No confirmation prompt is shown by default when deleting sheets via VBA.
  • This is unlike the usual manual deletion in Excel, where a warning asks if you’re sure you want to delete the sheet.
  • Because of this, data loss can happen unintentionally if you delete the wrong sheet or don’t verify first.

Best Practice Suggestion:

To avoid accidental deletion, especially in automated processes, it’s wise to:

  • Check if the worksheet exists before deleting.
  • Display a confirmation prompt before executing the Delete command.
  • Temporarily disable the alert prompt and restore it afterward:
Sub SafeDeleteSheets()
    Application.DisplayAlerts = False
    If WorksheetExists("New") Then Worksheets("New").Delete
    If WorksheetExists("Sheet1_Copy") Then Worksheets("Sheet1_Copy").Delete
    Application.DisplayAlerts = True
End Sub
Function WorksheetExists(sheetName As String) As Boolean
    On Error Resume Next
    WorksheetExists = Not Worksheets(sheetName) Is Nothing
    On Error GoTo 0
End Function

This version avoids runtime errors if a sheet doesn’t exist and prevents Excel from displaying the default warning for each deletion.

0 0 votes
Évaluation de l'article
S’abonner
Notification pour
guest
0 Commentaires
Le plus ancien
Le plus récent Le plus populaire
Online comments
Show all comments
Facebook
Twitter
LinkedIn
WhatsApp
Email
Print
0
We’d love to hear your thoughts — please leave a commentx