Search code examples
vbadeclarefilesystemobject

What is the correct way to declare and define a FileSystemObject object on VBA?


I was reading about how to declare FileSystemObjects objects and I found confusing information. Is it because there are different ways to declare it?

I let you some of the ways I found to declare and define FileSystemOjbect objects:

  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")

Which is the right way to declare FileSystemObject objects?


Solution

  • All 3 ways are correct. You have hit 2 different approaches to using objects.

    • The former 2 ways mean "Early Binding".
    • The last way means "Late Binding".

    The middle way is about a shortcut to the the 1st way, but not fully. It is better avoided by novice VBA users in complex code, as any reference to the object variable creates a new instance of the object, if the object variable=Nothing

    Early binding: One has to have linked the used libraries/modules in VBA - Tools - References, in this time Microsoft Scripting Runtime Library If the module/code is not present on the target computer, execution will fail. Early binding is reportedly significantly faster. Early binding offers at development the Intellisense-editor suggestion of object methods and properties and named constants

    Late Binding: No need of linking used external libraries/modules - better intermachine portability. Late binding is reportedly slower. Late binding does not offer Intellisense and the object specific constants has to be either explicitly declared either provided by their value.

    See e.g. a conditional code compilation, based on the Project-wide conditional compilation argument 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

    See also

    https://wordmvp.com/FAQs/InterDev/EarlyvsLateBinding.htm

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