Search code examples
vbatagspowerpointslide

Searching for a slide with a specified tag and replacing it with a slide from a master presentation


I am looking to search a presentation for a slide or slides that have a specified tag. Once found, I would like to replace the slide with another slide from a master presentation.

I have attempted to create a solution with parts of other VBA I have collected. I sense I am close but am not there yet (note the below gets me stuck in a loop).

Any help would be gratefully received

Sub ReplaceSlideThatHasTag()


For Each osld In ActivePresentation.Slides

'here I am selecting the slide that has the tag name "winter" and the tag id "123
If osld.Tags("WINTER") = "123" Then osld.Select

'here I am trying to add slide 27 from my master presentation immediately before the slide with the tag
ActivePresentation.Slides.InsertFromFile ("C:\my files\master presentation.PPTX"), ActiveWindow.Selection.SlideRange.SlideIndex, 24, 24

'and finally I am looking to delete the slide with the tag
If osld.Tags("WINTER") = "123" Then osld.Delete


Next osld

End Sub

Solution

  • A bit of general advice: Never select anything unless you can't avoid it, and it's almost never the case that you can't avoid it. Suggestions (with commments) below. Give this version a try.

    Sub ReplaceSlideThatHasTag()
    
    ' ALWAYS dim your variables before using them
    Dim osld as Slide
    
    For Each osld In ActivePresentation.Slides
    
    'here I am selecting the slide that has the tag name "winter" and the tag id "123
    
    If osld.Tags("WINTER") = "123" Then '  DON'T select anythin osld.Select
    
    'here I am trying to add slide 27 from my master presentation immediately before the slide with the tag
    'ActivePresentation.Slides.InsertFromFile ("C:\my files\master presentation.PPTX"), 'ActiveWindow.Selection.SlideRange.SlideIndex, 24, 24
    
    ' But since we're not selecting anything ...
    ActivePresentation.Slides.InsertFromFile ("C:\my files\master presentation.PPTX"), _ osld.SlideIndex
    
    'and finally I am looking to delete the slide with the tag
    ' But we already have a reference to the slide in the osld variable
    ' and we know that the slide has the tag so ...
    'If osld.Tags("WINTER") = "123" Then osld.Delete
    osld.Delete
    
    ' And since we've found the slide and done the deed,
    ' no need to continue...
    Exit For
    End If
    Next osld
    
    End Sub