I have some MS Word VBA which runs 10x more slowly when adapted to run within Outlook 2016. I'm hoping someone to help me identify why that might be the case. Tomalak developed the VBA code in this question (which deletes all but one duplicated paragraphs in a Word document) which I adapted to be able to be run on a Message in Outlook 2016. My adapted code is below:
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
Hopefully it is clear that the section denoted 'Inserted Modified Word VBA' is the original Word VBA code with the 4 modifications indicated by remarks beginning 'In Word VBA was.....'. I also added the top section of the code 4xdims and 4xsets to allow the code to run in Outlook.
The original code runs perfectly in Word 2010 x86, and the modified code runs perfectly in Outlook 2016 x86. I am at a loss as to why when run in Outlook it should be so much slower. (In Outlook the Word 2016 Object Library and the MS Scripting Runtime have both been referenced)
[NB: To avoid any confusion I have also posted a question with a similar title on at EE. this relates to different code. If either post yields useful results I will cross-post in both venues.]
objWord
is an object an not a libary (that is Word) that contains the Paragraph class inDim p As objWord.Paragraph
. It should beDim p As Word.Paragraph
. I don't know why the code runs slower (if it does), but maybe the Word inspector in Outlook is slower? Try if is faster when you create a "real" Word instance copy the Text, remove the paragraphs and copy it back to outlook. – ComputerVersteher