excelvbafilesystemobjectreference-library

Setting FSO to FileSystemObject vs Scripting.FileSystemObject


I just had one of those moments where you step out of the weeds and examine your code and ask yourself "why did I do that?"

I have a script that creates a folder with several subfolders and files using the FileSystemObject. Everything works, but I guess I've been varying the way I set my fso variables.

My project uses the the Microsoft Scripting Runtime Library reference so that I can use early binding (even though I found several instances of Set fso = CreateObject("Scripting.FileSystemObject"), which is silly for this project). Perhaps it's because I've based a lot of my code from examples online, but I've been setting these fso variables in one of two ways:

Set FSo = New FileSystemObject

Set FSo = New Scripting.FileSystemObject

What is the difference between these? Does it matter which I use, or is one used only in certain cases?


Solution

  • The difference between these is that the latter disambiguates the FileSystemObject to belong to Scripting and not to something else.

    If you had your own class named FileSystemObject in that workbook, the latter would be required to specify you are creating the Scripting.FileSystemObject and not Yourworkbook.FileSystemObject.

    Similarly, if you had a reference to some other external library that also featured a class named FileSystemObject, it would resolve that ambiguity too. That is why there are up/down arrows in the Add Reference dialog - they decide which library wins in the case of a clashed name and no explicit disambiguation from the coder.

    A common case in VBA where the disambiguation is needed is working with Word and Excel object models at the same time. Both have a class called Range, and you often need to specify whether you want Word.Range or Excel.Range this time.

    If you don't have any such conflicting names, it makes no difference for you, apart from maybe making it a tad easier for the future reader to recall that FileSystemObject is that thing from Scripting.