自适应Word VBA代码在Outlook 2016中运行非常慢

时间:2018-07-21 11:21:19

标签: vba outlook ms-word word-vba outlook-vba

我有一些MS Word VBA,在适应于Outlook 2016中运行时,它的运行速度慢了10倍。我希望有人帮助我确定为什么会这样。 Tomalak在此问题中开发了VBA代码(它删除了Word文档中除一个重复的段落外的所有段落),我使其能够在Outlook 2016中的邮件上运行。我的适应代码如下:

Public Sub STRIPPER_RepeatedTextParasTomalakSimple()
' Add ref to Word Object library and
' MS Scripting Runtime in VBA Editor, Tools, References
Dim objInsp As Outlook.Inspector
Dim objDoc As Word.Document
Dim objWord As Word.Application
Dim Selection As Word.Selection

Set objInsp = Application.ActiveInspector
Set objDoc = objInsp.WordEditor
Set objWord = objDoc.Application
Set objSel = objWord.Selection

'------- Inserted Modifed Word VBA below ---------
  Dim p As Word.Paragraph        ' In Word VBA was '....As Paragraph'
  Dim d As New Scripting.Dictionary
  Dim t As Variant
  Dim i As Integer
  Dim StartTime As Single

  StartTime = Timer

  ' collect duplicates
  For Each p In objDoc.Paragraphs    ' In Word VBA was '...In ActiveDocument.Paragraphs
    t = p.Range.Text
    If _
        t <> vbCr Then
        If Not d.Exists(t) Then d.Add Key:=t, Item:=New Scripting.Dictionary
        d(t).Add Key:=d(t).Count + 1, Item:=p
    End If
  Next p

  ' eliminate duplicates
  objWord.ScreenUpdating = False     ' In Word VBA was 'Application.Screenupdating = False'

  For Each t In d
    For i = 1 To d(t).Count - 1
        d(t)(i).Range.Delete         ' This line is the bottleneck
      Next i
  Next t
  objWord.ScreenUpdating = True      ' In Word VBA was 'Application.Screenupdating = True'

MsgBox "This code ran successfully in " & Round(Timer - StartTime, 2) & " seconds", vbInformation
objUndo.EndCustomRecord
'------- End of Modifed Word VBA above ---------


End Sub

希望很明显,标记为“插入的修改的单词VBA”的部分是原始的Word VBA代码,带有以“在Word VBA中是.....”开头的注释指示的4个修改。我还添加了代码4xdims和4xsets的顶部,以允许代码在Outlook中运行。

原始代码可以在Word 2010 x86中完美运行,而修改后的代码可以在Outlook 2016 x86中完美运行。我不知为何要在Outlook中运行它时要慢得多。 (在Outlook中,已经引用了Word 2016对象库和MS脚本运行时)

[NB:为避免引起混淆,我还在EE.上贴了一个标题相似的问题,该问题与不同的代码有关。如果任何一个发布都能产生有用的结果,我都会在两个地点交叉发布。]

1 个答案:

答案 0 :(得分:1)

肯·怀特(Ken White)的评论回答了这个问题,但是我想添加它作为回答,以防再次被问到。肯说

“在Word中执行的代码没有使Word自动化的开销。Outlook代码具有这种开销,因为它必须将工作传递给Word并等待结果。自动化的代码永远不会像直接运行的代码。与您向其他人解释所需的工具并等待他们将其交付给您相比,您花费更少的时间亲自从工作台中拿起工具。 >