Search code examples
vbapowerpoint

Is there a way with VBA to capture when a PowerPoint slide is DELETED


I already have code with runs when a PowerPoint slide is added to a presentation but I cannot find a way to capture when a slide is deleted. I wondered if anyone had any ideas please?

I've looked through the WithEvents list but cannot find one that appears right.


Solution

  • There is no such event in PowerPoint :-(

    How the code works

    • implement a slide counter
    • whenever SlideSelectionChanged fires, current slides count is compared to the counter - if less at least one slide must have been deleted. SlideSelectionChanged fires when deleting a slide as a different slide gets selected after deletion.

    Put this code into your Application class.

    Private WithEvents objApp As Application
    
    Private Sub Class_Initialize()
    Set objApp = Application
    On Error Resume Next
        'When addin starts there is no activepresentation
        If Application.Presentations.Count > 0 Then
            If Not ActivePresentation Is Nothing Then
                initSlideCounter ActivePresentation
            End If
        End If
    On Error GoTo 0
    End Sub
    
    Private Sub initSlideCounter(p As Presentation)
    p.Tags.Add "CNTSLIDES", p.Slides.Count
    End Sub
    
    Private Property Get SlideCounter(p As Presentation) As Long
    On Error Resume Next
    SlideCounter = p.Tags("CNTSLIDES")
    If Err <> 0 Then
        initSlideCounter p
        SlideCounter = p.Tags("CNTSLIDES")
    End If
    On Error GoTo 0
    End Property
    
    Private Sub objApp_SlideSelectionChanged(ByVal SldRange As SlideRange)
    Dim p As Presentation: Set p = SldRange.Parent
    
    If p.Slides.Count < SlideCounter(p) Then
        MsgBox "at least one slide has been deleted"
        initSlideCounter p    'slide deleted
    End If
    
    End Sub
    
    Private Sub objApp_NewPresentation(ByVal Pres As Presentation)
    initSlideCounter Pres
    End Sub
    
    Private Sub objApp_PresentationOpen(ByVal Pres As Presentation)
    initSlideCounter Pres
    End Sub
    
    Private Sub objApp_PresentationNewSlide(ByVal sld As Slide)
    initSlideCounter sld.Parent
    End Sub