This answer is probably too late to assist the poster, but is provided to clear up the question.
The example code in the question comes straight from the Powerpoint VBA help file - but it is incorrect. Attempting to run it as written leads to an infinite loop. The FindFirst function does not return
Nothing for the textrange object value if there is no match in the tests I have performed (on PowerPoint 2007). Instead it returns an empty string. In addition to this problem, on the last occurrence of the text concerned Find repeatedly cycles between the start of the last matching text range and the end, again creating an infinite loop.
The revised code below correctly terminates for any number of instances of the text "CompanyX" included on slides in a presentation.
- Sub searchMacro()
-
Dim sld As Slide
-
Dim shp As Shape
-
Dim txtRng As TextRange
-
Dim foundtext As TextRange
-
Dim lngStart As Long
-
For Each sld In Application.ActivePresentation.Slides
-
For Each shp In sld.Shapes
-
If shp.HasTextFrame Then
-
Set txtRng = shp.TextFrame.TextRange
-
lngStart = 0
-
Set foundtext = txtRng.Find(FindWhat:="CompanyX")
-
Do While Not (foundtext = "") And (foundtext.Start > lngStart)
-
With foundtext
-
.Font.Bold = True
-
Set foundtext = _
-
txtRng.Find(FindWhat:="CompanyX", _
-
After:=.Start + .Length - 1)
-
lngStart = .Start
-
End With
-
Loop
-
End If
-
Next
-
Next
-
End Sub
Although I have not yet found how to move the cursor itself to the first occurrence of the text concerned, the first occurrence of the search text can be selected using the following sub (again based on the 'CompanyX' exemplar in the helpfile).
- Sub SelectFirst()
-
Dim sld As Slide
-
Dim shp As Shape
-
Dim txtRng As TextRange
-
Dim foundtext As TextRange
-
Dim lngStart As Long
-
For Each sld In Application.ActivePresentation.Slides
-
For Each shp In sld.Shapes
-
If shp.HasTextFrame Then
-
Set txtRng = shp.TextFrame.TextRange
-
lngStart = 0
-
Set foundtext = txtRng.Find(FindWhat:="CompanyX")
-
If foundtext <> "" Then
-
sld.Select
-
shp.Select
-
foundtext.Select
-
Exit Sub
-
End If
-
End If
-
Next
-
Next
-
End Sub
Note that for the Select method of the textrange object to work correctly the slide and shape objects concerned must be selected first, as shown. If you omit those steps a run-time error occurs due to failure to select the outer objects before trying to select the inner textrange object.
To generalise the search, replace the string literal "CompanyX" in the code above with a reference to an appropriately-set string variable containing the search term you are looking for.
-Stewart