如何使用 VBA 在 powerpoint 中查找和替换字符串

How to find and replace a string in powerpoint using VBA

我想将 ppt 幻灯片 1 中的 "hello" 替换为 "world"。我如何使用 VBA 脚本来做到这一点。

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

在对上一个答案的一个小补充中,在office 2016中,我使用了以下方法来实现同样的事情,但是这种方法让我可以在文本范围内保持格式,因为它只替换搜索的特定文本:

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