【问题标题】:How to make "edit links" VBA code run faster?如何使“编辑链接”VBA 代码运行得更快?
【发布时间】:2019-06-06 12:36:11
【问题描述】:

我编写了一些代码来查找“文件 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

【问题讨论】:

  • oshp.LinkFormat.Update - 删除此操作?因为我认为这是主要的问题领域。否则,每次都会出现这样的问题,因为 PowerPoint 可能需要从那些 excel 文件中抓取数据
  • 您是否尝试过逐行浏览代码?您会发现哪条线路占用的时间最多。
  • 尝试ActivePresentation.UpdateLinks For Each 循环之外。这将更新 pp 中的所有链接一次,而不是在每次迭代期间更新
  • “文件 B”是否打开?如果不是,PowerPoint 将继续打开和关闭它。在开始之前打开它(在代码中或手动)。如果“文件 B”链接到其他文件,那么所有这些都需要打开。
  • 同上@Gareth 所说的!在代码中同时打开File AFile B然后开始重新链接。它不会很快,但这样会更快。

标签: excel vba powerpoint


【解决方案1】:

这段代码非常干净,因此您可能无法优化它,但我会提醒您,它所做的不仅仅是“查找和替换文本”:) 每次调用 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

【讨论】:

  • If oshp.Type = msoLinkedOLEObject Then 赞不绝口 - 在尝试更新未链接的对象时节省了大量精力。
  • 谢谢!立即尝试这些更改
  • 有没有办法修改 IF 语句以同时运行图表代码?虽然大多数链接都在 OLE 对象中,但也有少量图表(代码将忽略)。
  • 试试If oshp.Type = MsoLinkedOLEObject Or oshp.Type = MsoChart?您可能需要重新添加On Error Resume Next,但请先尝试不添加,看看是否会导致任何错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-18
  • 2020-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-28
相关资源
最近更新 更多