首页 > 解决方案 > 如何使“编辑链接”VBA 代码运行得更快?

问题描述

我编写了一些代码来查找“文件 A”的外部链接,并将它们替换为“文件 B”的链接。代码在PowerPoint中,“文件A”和“文件B”都是excel文件。PowerPoint 文件有大约 25 个“对象”链接到 excel(这些对象主要只是作为链接对象粘贴到 PowerPoint 中的 excel 单元格)。

代码有效,但运行需要 7-8 分钟。知道为什么需要这么长时间或如何使其更快吗?似乎它所做的只是查找和替换文本,所以我很困惑为什么需要这么多时间。

代码的相关部分:

Dim newPath As String
Dim templateHome As String
Dim oshp As Shape
Dim osld As Slide
Dim vizFile As Workbook
Dim vizFname As String
Dim replacethis As String
Dim replacewith As String


'3. Update links:
'(Replace links to template file link with links to new copy of the file)


replacethis = templateHome & vizFname
replacewith = newPath & "\" & vizFname
On Error Resume Next
For Each osld In ActivePresentation.Slides
   For Each oshp In osld.Shapes


     oshp.LinkFormat.SourceFullName = Replace(oshp.LinkFormat.SourceFullName, replacethis, replacewith)
     oshp.LinkFormat.Update


    Next oshp
Next osld

标签: excelvbapowerpoint

解决方案


这段代码非常干净,因此您可能无法对其进行很多优化,但我会提醒您,它所做的不仅仅是“查找和替换文本”:) 每次调用都会UpdateLink从某个外部源检索数据。这不仅仅是简单的字符串替换!

首先:On Error Resume Next正在吞下很多错误(即,任何不是链接对象的形状,因此,它们中的大多数),这可能会增加您的运行时间,如果您围绕这些错误进行编码而不是仅仅使用Resume Next.

' On Error Resume Next ' ## Comment or remove this line :)
For Each osld In ActivePresentation.Slides
    For Each oshp In osld.Shapes
        If oshp.Type = msoLinkedOLEObject Then
            oshp.LinkFormat.SourceFullName = Replace(oshp.LinkFormat.SourceFullName, replacethis, replacewith)
            oshp.LinkFormat.Update
        End If
    Next
Next

另外,您正在oshp.LinkFormat.Update反复调用。在循环中替换所有文本可能会更好,但不要更新单个链接,而是使用以下Presentation.UpdateLinks方法在循环外一次更新它们:

' On Error Resume Next ' ## Comment or remove this line :)
For Each osld In ActivePresentation.Slides
    For Each oshp In osld.Shapes
        If oshp.Type = msoLinkedOLEObject Then
            oshp.LinkFormat.SourceFullName = Replace(oshp.LinkFormat.SourceFullName, replacethis, replacewith)
            ' ## REMOVE oshp.LinkFormat.Update
        End If
    Next
Next
' Now, update the entire presentation:
ActivePresentation.UpdateLinks

推荐阅读