在VBA上声明和定义FileSystemObject对象的正确方法是什么?

问题描述 投票:0回答:1

我正在阅读有关如何声明FileSystemObject对象的文章,我发现了令人困惑的信息。是因为有不同的方式来宣布它吗?

我告诉你我发现的一些声明和定义FileSystemObject对象的方法:

  1. Dim FSO As FileSystemObject Set FSO = New FileSystemObject
  2. Dim FSO As New FileSystemObject
  3. Dim FSO As Object Set FSO = CreateObject("scripting.filesystemobject")

哪个是声明FileSystemObject对象的正确方法?

vba declare filesystemobject
1个回答
1
投票

所有3种方式都是正确的。您已经使用了两种不同的方法来使用对象。

  • 前两种方式意味着“早期绑定”。
  • 最后一种方式意味着“后期绑定”。

中途是第一种方式的捷径,但并不完全。复杂代码中的新手VBA用户最好避免使用,因为对象变量的任何引用都会创建对象的新实例,如果对象变量= Nothing

早期绑定:必须链接VBA中使用的库/模块 - 工具 - 引用,此时Microsoft脚本运行时库如果目标计算机上不存在模块/代码,则执行将失败。据报道早期结合明显更快。早期绑定在开发时提供了Intellisense-editor对象方法和属性以及命名常量的建议

后期绑定:无需链接使用的外部库/模块 - 更好的机器间可移植性。据报道,后期绑定较慢。后期绑定不提供Intellisense,并且对象特定常量必须由其值显式声明。

参见例如条件代码编译,基于项目范围的条件编译参数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://wordmvp.com/FAQs/InterDev/EarlyvsLateBinding.htm

https://support.microsoft.com/en-gb/help/245115/using-early-binding-and-late-binding-in-automation

© www.soinside.com 2019 - 2024. All rights reserved.