问题
I would like to replace the word "hello" with "world" on slide 1 of the ppt. How can I do that using VBA script.
回答1:
Sub findAndReplaceText()
Dim sld As Slide
Set sld = ActivePresentation.Slides(1)
Dim shp As Shape
For Each shp In sld.Shapes
If shp.HasTextFrame Then
If shp.TextFrame.HasText Then
shp.TextFrame.TextRange.Text = Replace(shp.TextFrame.TextRange.Text, "hello", "world")
End If
End If
Next shp
End Sub
Reference: https://www.youtube.com/watch?v=BYfKvVmtAGE
回答2:
In a slight addendum to the previous answer, in office 2016, I used the following method to achieve the same thing, however this method lets me keep formatting within the text range, as it only replaces the specific text searched for:
Sub findAndReplaceText(sld As PowerPoint.Slide, findText As String, replaceText As String)
Dim shp As PowerPoint.Shape
Dim textLoc As PowerPoint.TextRange
For Each shp In sld.Shapes
If shp.HasTextFrame Then
If shp.TextFrame.HasText Then
Set textLoc = shp.TextFrame.TextRange.Find(findText) 'use Find function to get the textrange for the string being searched for
If Not (textLoc Is Nothing) Then 'if something is found
textLoc.Text = replaceText 'then replace it
End If
End If
End If
Next shp
End Sub
来源:https://stackoverflow.com/questions/42555956/how-to-find-and-replace-a-string-in-powerpoint-using-vba