【问题标题】:How to find and replace a string in powerpoint using VBA如何使用 VBA 在 powerpoint 中查找和替换字符串
【发布时间】:2017-03-02 12:47:13
【问题描述】:

我想在 ppt 的幻灯片 1 上用“世界”代替“你好”这个词。如何使用 VBA 脚本做到这一点。

【问题讨论】:

  • 我建议您阅读Getting Started with VBA in PowerPoint 2010 之类的内容,然后尝试自己编写一些代码。如果您遇到困难,请向我们展示您的所作所为,以便我们提供帮助。
  • 实际上,我是 VBA 新手,之前已经做过一些研究,但是我没有找到我需要的正确信息。你能分享一下例子吗?
  • 查看此示例:skphub.com/ppt00025.htm#2

标签: vba powerpoint


【解决方案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

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

【讨论】:

  • 请注意,这不会在表格、smartart、分组形状、图表等中查找/替换文本。
  • 请注意,这不会保留任何特定于行或节的格式,因为它会替换形状中的所有文本
  • 除了检查 HasText 之外,您还需要避免分组项目,因为它们会在 TextRange 上失败。 -> 如果 shp.TextFrame.HasText 和 shp.Type msoGroup 则
【解决方案2】:

在上一个答案的一个小补充中,在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    相关资源
    最近更新 更多