3种方式都是正确的。您已经找到了两种不同的使用对象的方法。
- 前两种方式的意思是“早期绑定”。
- 最后一种方式意味着“后期绑定”。
中间道路是第一种道路的捷径,但并不完全。
新手 VBA 用户最好避免使用复杂的代码,
因为对对象变量的任何引用都会创建该对象的新实例,
如果对象变量=Nothing
早期绑定:
必须在 VBA - 工具 - 参考中链接使用的库/模块,
在这段时间微软脚本运行时图书馆
如果目标计算机上不存在该模块/代码,则执行将失败。
据报道,早期绑定速度明显更快。
早期绑定在开发过程中提供了对象方法和属性以及命名常量的智能感知编辑器建议
后期绑定:
无需链接使用的外部库/模块 - 更好的机器间可移植性。
据报道,后期绑定速度较慢。
后期绑定不提供智能感知,并且对象特定常量必须显式声明或由其值提供。
参见例如条件代码编译,基于项目范围的条件编译参数 Earlybinding :
Sub EarlyVsLateBindingtest()
#If Earlybinding Then
Dim oFS As Scripting.FileSystemObject
Set oFS = New Scripting.FileSystemObject
#Else
Const TemporaryFolder = 2
Dim oFS As Object
Set oFS = CreateObject("Scripting.FileSystemObject")
#End If
oFS.GetSpecialFolder (TemporaryFolder)
End Sub
https://superuser.com/questions/615463/how-to-avoid-references-in-vba-early-binding-vs-late-binding/1262353?noredirect=1#comment1859095_1262353 https://superuser.com/questions/615463/how-to-avoid-references-in-vba-early-binding-vs-late-binding/1262353?noredirect=1#comment1859095_1262353
See also
https://wordmvp.com/FAQs/InterDev/EarlyvsLateBinding.htm https://wordmvp.com/FAQs/InterDev/EarlyvsLateBinding.htm
https://support.microsoft.com/en-gb/help/245115/using-early-binding-and-late-binding-in-automation https://support.microsoft.com/en-gb/help/245115/using-early-binding-and-late-binding-in-automation