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

时间:2017-03-02 12:47:14

标签: vba powerpoint powerpoint-vba

我想在ppt的幻灯片1中将“hello”替换为“world”。我怎么能用VBA脚本做到这一点。

2 个答案:

答案 0 :(得分:7)

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
  

参考:https://www.youtube.com/watch?v=BYfKvVmtAGE

答案 1 :(得分:0)

在上一个答案的略微补充中,在2016年的办公室中,我使用以下方法来实现相同的功能,但是这种方法可以让我在文本范围内保持格式化,因为它只替换搜索到的特定文本: / p>

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