繁体   English   中英

以编程方式编辑 PowerPoint 演示文稿中的文本

[英]Programmatically editing text in a powerpoint presentation

我需要编写一个程序,该程序可以遍历演示文稿并将文本字符串的所有实例更改为不同的实例。 因此,例如,无论何时出现文本字符串“旧公司名称”,它都会将其替换为“新公司名称”。

我对如何自动化 Powerpoint 有了大致的了解,挑战在于很难遍历 shape 对象,而且我看不到存储此数据的明显属性(例如,“文本”属性。)

有人可以指出我正确的方向吗?

另外,有没有一个工具可以更容易地挖掘Office产品的对象模型,也就是说遍历特定文档的实例对象树? 通常我会用 Visual Studio 调试器来做这件事,但因为它是 COM 之上的一个薄层,你不能像在其他情况下那样在监视窗口中轻松地遍历对象实例树。 有没有好的工具可以帮助解决这个问题?

PPT 2010 如果重要的话。

Powerpoint 是自动化(使用 VBA)的更棘手的 Office 应用程序之一,因为您无法像使用 Word 和 Excel 那样录制宏。 我发现学习对象模型的最佳方法是将 Web 搜索和对象浏览器与 VBIDE(只需按 F2)相结合。

至于文本替换,一旦你知道,这是一个简单的例子。 您可以循环浏览特定幻灯片中的所有形状,然后检查该形状的文本。 (请注意,此代码实际上来自 Excel 工作簿,因此它包含Powerpoint中不需要的Powerpoint引用:

编辑:史蒂夫对原始编辑仅搜索文本框提出了一个很好的观点,根据您的演示设置,您必须单独对每种类型的对象进行排序,并对每种类型实施自定义替换。 不是特别困难,只是背部疼痛。

另请注意,根据演示文稿的大小,循环浏览所有形状可能需要一段时间。 我还使用了.HasTextFrame / .HasTable.Type的组合,因此您可以看到这两种类型。

Sub ReplaceTextShape(sFindText As String, sNewText As String, ppOnSlide As PowerPoint.Slide)
    Dim ppCurShape As PowerPoint.Shape

    For Each ppCurShape In ppOnSlide.Shapes
        If ppCurShape.HasTextFrame Then
            ppCurShape.TextFrame.TextRange.Text = VBA.Replace(ppCurShape.TextFrame.TextRange.Text, sFindText, sNewText)
        ElseIf ppCurShape.HasTable Then
            Call FindTextinPPTables(ppCurShape.Table, sFindText, sNewText)
        ElseIf ppCurShape.Type = msoGroup Then
            Call FindTextinPPShapeGroup(ppCurShape, sFindText, sNewText)
            ''Note you'll have to implement this function, it is an example only
        ElseIf ppCurShape.Type = msoSmartArt Then
            Call FindTextinPPSmartArt(ppCurShape, sFindText, sNewText)
            ''Note you'll have to implement this function, it is an example only
        ElseIf ppCurShape.Type = msoCallout Then
            'etc
        ElseIf ppCurShape.Type = msoComment Then
            'etc etc
        End If
    Next ppCurShape

    Set ppCurShape = Nothing
End Sub

然后替换整个演示文稿中的所有文本:

Sub ReplaceAllText(ppPres As PowerPoint.Presentation)
    Dim ppSlide As PowerPoint.Slide

    For Each ppSlide In ppPres.Slides
        Call ReplaceTextShape("Hello", "Goodbye", ppSlide)
    Next ppSlide

    Set ppSlide = Nothing
End Sub

以及替换表格中文本的示例代码:

Sub FindTextinPPTables(ppTable As PowerPoint.Table, sFindText As String, sReplaceText As String)
    Dim iRows As Integer, iCols As Integer

    With ppTable
        iRows = .Rows.Count
        iCols = .Columns.Count

        For ii = 1 To iRows
            For jj = 1 To iCols
                .Cell(ii, jj).Shape.TextFrame.TextRange.Text = VBA.Replace(.Cell(ii, jj).Shape.TextFrame.TextRange.Text, sFindText, sReplaceText)
            Next jj
        Next ii
    End With

End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM