How to find and replace a string in powerpoint using VBA

安稳与你 提交于 2019-12-08 15:26:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!