Home » excel » excel – Delete Sheet/chart event VBA

excel – Delete Sheet/chart event VBA

Posted by: admin April 23, 2020 Leave a comment


I am trying to trigger a macro when a sheet (Excel) is deleted.
Since 2010 there are different delete events:

Application Level: The Application.SheetBeforeDelete event.

Workbook Level: The Workbook.SheetBeforeDelete event.

Worksheet Level: The Worksheet.BeforeDelete event.

As a beginner I was not able to apply the last two well, however I tried to apply the first one.

Private Sub Workbook_SheetBeforeDelete(ByVal Sh As Object) 
Call Macro
End Sub

This works fine on sheets, but it doesn’t work on charts (sheets that only contain a chart).

My goal is to adjust my counter and possibly rename the sheets, as my sheets are named Sheetname(1),..(2).. and the user frequently deletes sheets.

I searched a lot but I couldn’t find any examples that I could follow.

Any help would be much appreciated.

How to&Answers:

It’s looks like an implementation oversight, this event should have been implemented according to the design. In fact, the Sheets collection is the union of the Worksheets and Charts collections. Since the name of the event is Workbook_SheetBeforeDelete (not Workbook_WorksheetBeforeDelete), common sense dictates that the event should apply to all Sheets, that is, both Worksheets and Charts.

Notice that, other events such as Workbook_SheetDeactivate are raised for both Charts and Worksheets. This confirms the error but also suggests a workaround by exploiting the Workbook_SheetDeactivate event.

We can add two procedures to ThisWorkbook code module. checkChartDelete() checks if a chart has been deleted and launches the appropriate action. It needs to be called through Application.OnTime, so it gets its parameter through a static variable chartNameToCheck.

' Code Module ThisWorkbook
Option Explicit
Private chartNameToCheck As String
Private Sub checkChartDelete()
    On Error Resume Next
    Dim x: Set x = Sheets(chartNameToCheck)
    If Err.Number <> 0 Then
        ' call or do here the action on chart deleted '
        MsgBox "chart deleted: " & chartNameToCheck
    End If
    chartNameToCheck = ""
End Sub

Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
    If TypeName(Sh) <> "Chart" Then Exit Sub
    chartNameToCheck = Sh.name
    Application.OnTime Now, "ThisWorkbook.checkChartDelete"
End Sub