Return the slide number when slide with specific title

gailb
3StarLounger
Posts: 256
Joined: 09 May 2020, 14:00

Return the slide number when slide with specific title

Post by gailb »

At first this working for me, but now if there are slides without a title it throws an error. I tried messing around with the On Error Resume, and it semi works. It does not error anymore when a slide has a blank title, but it also does not find the right slide. The slide with the proper title is slide 16, but this tells me it's slide 30 which does not even have a slide title. Of course, if I remove all slide without a title in returns slide 16.

Code: Select all

Sub TestMe()
    Dim oSl As Slide: Set oSl = FindSlideByTitle("WORSHIP SERVICE")
    If Not oSl Is Nothing Then MsgBox "Found your title on slide " & CStr(oSl.SlideIndex)
End Sub

Code: Select all

Function FindSlideByTitle(sTextToFind As String) As Slide
    Dim oSl As Slide
    For Each oSl In ActivePresentation.Slides
        With oSl.Shapes.Title.TextFrame
        On Error Resume Next
            If .HasText Then
                If UCase(.TextRange.Text) = UCase(sTextToFind) Then
                    Set FindSlideByTitle = oSl
                End If
            End If
        End With
    Next
End Function

User avatar
HansV
Administrator
Posts: 78947
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Return the slide number when slide with specific title

Post by HansV »

You forgot to exit the For ... Next loop once the slide has been found:

Code: Select all

Function FindSlideByTitle(sTextToFind As String) As Slide
    Dim oSl As Slide
    For Each oSl In ActivePresentation.Slides
        With oSl.Shapes.Title.TextFrame
            If .HasText Then
                If UCase(.TextRange.Text) = UCase(sTextToFind) Then
                    Set FindSlideByTitle = oSl
                    Exit For
                End If
            End If
        End With
    Next
End Function
Best wishes,
Hans

gailb
3StarLounger
Posts: 256
Joined: 09 May 2020, 14:00

Re: Return the slide number when slide with specific title

Post by gailb »

So, I don't need the On Error, or does it still need to be included?

User avatar
HansV
Administrator
Posts: 78947
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Return the slide number when slide with specific title

Post by HansV »

You still need it to avoid an error if there are slides without a title shape.
Best wishes,
Hans

gailb
3StarLounger
Posts: 256
Joined: 09 May 2020, 14:00

Re: Return the slide number when slide with specific title

Post by gailb »

Got it thanks.