Alternate Title: Why does pressing Esc make my MS-Word macro run faster
在等待一些代码运行时,我偶然发现了一些有趣的事情。
Code runs slow... press Esc code runs fast. Example:
- press Esc immediately after execution - 2 sec to complete
- don't press Esc at all - up to 30 sec to complete
对我来说这毫无意义。事实证明其他人也注意到了类似的行为,例如:
And they have found various solutions or workarounds. However, these posts are for MS-Excel; which it seems has different behavior for the Esc key.
In MS-Excel pressing the Esc key can (depending on the setting of Application.EnableCancleKey) interrupt code or raise an error (Err 18), or do nothing. On the other hand in MS Word no such thing happens, instead Application.EnableCancleKey alters the behavior of Ctrl + Pause. Yet despite this, pressing the Esc speeds up the code execution dramatically.
除了这种差异之外,我的问题更多地与用户窗体中的代码放置有关。例如在我的用户表单中:
Private Sub Cmd_Click()
Module1.Macro1
Module1.Macro2
Module1.Macro3
End Sub
在 64 位版本的 Word 2010 上测试,使用上面的结构明显比这个慢:
用户表单:
Private Sub Cmd_Click()
Module1.RunMacro123
End Sub
标准模块:
Private Sub RunMacro123()
Module1.Macro1
Module1.Macro2
Module1.Macro3
End Sub
我应该注意以下几点:
- 这在 64 位版本的 MS Word 中最为明显,32 位版本似乎使用原始代码运行得相当快(我还没有使用修改后的代码进行测试)
- 就像第一个链接中的作者一样,我没有使用选择对象等。
- I'm more interested any insights as to why the speed of code execution is so influenced by:
- pressing Esc
- 将调用从用户窗体转移到标准模块
- Macro1、Macro2 和 Macro3 创建和编辑文档样式(FWIW)涉及多次读取 INI 文件
On a side note, in a hair-brained attempt at being clever I tried using sendKeys to send the Esc key but it has no affect.
编辑 - 代码计时结果:
我最终使用计时器函数来计时代码,我已经实现了一个堆栈类,该类是从这里改编的:http://www.tek-tips.com/viewthread.cfm?qid=1468970
我添加了一个“绝对”计时器(debug.print timer - startTime
)到调用堆栈,以便记录每次推送之间的时间并重置计时器(startTime = timer
)在每次弹出。这样做可以使在 NotePad++ 中比较时间变得更容易
这使我能够确定将样式应用于文档的子程序花费了约 0.04 秒的时间来应用样式(计时器返回的 NB 值 = 午夜过后的秒数)。
The image below shows an example of the code timing results. Basically, as far as I can tell, the delay in code execution comes from many incremental delays all associated with the same basic task.
由于计时器与调用堆栈的工作方式,我必须测试代码getStyleElement
以确保它不会对加时赛产生重大影响。我通过直接对代码计时来做到这一点,并能够确认它的运行速度始终很快。
检查其余代码确认问题出在applyStyleFormat
(这称为getStyleElement
).
样式应用于文档 - 代码结构包括 With 块和 For 循环;像这样的东西:
For i = 1 to Styles.Count
With aDocument.Styles(i)
.Font.??? = Something
' or .Paragraph.??? = Something
End With
Next i
I'm no clearer as to why the code runs faster from outside of the userform, or after pressing Esc but it does and it seems to have something to do with modifying styles...