【发布时间】:2023-03-09 12:30:01
【问题描述】:
我正在编写一个强大的 Word 宏,该宏将用于几台不同机器上的各种单词。
我在许多 VBA 专家论坛上阅读过,就性能而言,早期绑定总是比后期绑定更受欢迎。
然而,就我的逻辑而言,它感觉如此 - 除非令人信服地证明了好处 - 在可用性方面正好相反,因为我不希望确保在它可能运行的所有机器上勾选这些库引用的痛苦。
我已经尝试过 `ThisWorkbook.VBProject.References.AddFromGUID "{420B2830-E718-11CF-893D-00A0C9054228}", 1, 0`。它将以编程方式添加引用,但随后需要在机器上启用安全信任以进行代码操作。
因此,我设置了一个测试来比较 1000 次早期和晚期 bindt 字典操作的运行。我也尝试过其他测试设置,例如 ScreenUpdating、DoEvents、Debug.Print,以查看每个设置的性能影响。
到目前为止,我看到的是,早期绑定与后期绑定本身在任何设置中都没有可测量的性能差异(任何运行之间的随机波动除外 10%)。
VBA Guru-s 我对您对这个故事的了解很感兴趣,那我为什么要使用早期绑定,或者它在现实生活中真的有这样的优势。
我的测试代码是这样的:
Sub HeadingDefinitionWords_test()
Application.ScreenUpdating = False
Dim tm As Long
tm = timeGetTime
Dim DefinitionRangeBackup As Range, DefinitionRange As Range
Dim kEy As Variant, i As Long, k As Integer
Dim TempList As Object: Set TempList = CreateObject("Scripting.Dictionary")
'Dim TempList As Scripting.Dictionary: Set TempList = New Scripting.Dictionary
For i = 1 To 1000
'Call HeadingDefinitionWords(Selection.Range.Duplicate, TempList)
'''
Set DefinitionRange = Selection.Range.Duplicate
Set DefinitionRangeBackup = DefinitionRange.Duplicate
'-
With DefinitionRange.Find: .ClearFormatting: .Text = "([a-z])([A-Z])"
.Forward = True: .Wrap = wdFindStop: .Format = False: .MatchCase = False: .MatchWholeWord = False: .MatchAllWordForms = False
.MatchSoundsLike = False: .MatchWildcards = True
End With
'-
With DefinitionRange: While .Find.Execute And .InRange(DefinitionRangeBackup)
'-
.Expand Unit:=wdWord
'-
If Not TempList.Exists(Trim(DefinitionRange.Text)) Then TempList.Add Trim(DefinitionRange.Text), Trim(DefinitionRange.Text)
'-
DefinitionRange.Collapse wdCollapseEnd
Wend: End With
'''
For Each kEy In TempList
'Debug.Print kEy
If k = 50 Then
'Debug.Print k
k = 1
Else
k = k + 1
End If
'DoEvents
Next
Next
Dim tma As Long
tma = timeGetTime
Debug.Print tma - tm
Application.ScreenUpdating = True
End Sub
【问题讨论】:
-
与其他操作的成本相比,在您的示例中调用字典的成本微不足道。这就是为什么您在早期绑定和后期绑定之间没有任何区别。
标签: vba performance binding ms-word