Elias Wick
Elias Wick

Reputation: 493

VBA - Access FileSystemObject without Dimming it as an object

I wonder if you can access an object without dimming it. Example below:

In order to access the FileSystemObject I would access it in the following way:

Dim fso As Object
fso = CreateObject("Scripting.FileSystemObject")

    If fso.FolderExists("C:\Folder")
        msgbox "Folder exists"
    End If

I am looking for a way to access it without having to dim it. Something along the lines of:

    If Scripting.FileSystemObject.FolderExists("C:\Folder")
        msgbox "Folder exists"
    End If

I have added the [Microsoft Scripting Runtime] as a reference to my project, if that helps with my issue.

Upvotes: 1

Views: 692

Answers (2)

Kostas K.
Kostas K.

Reputation: 8518

This is also valid:

Late-bound:

With CreateObject("Scripting.FileSystemObject")
    If Not .FolderExists(path_) Then .CreateFolder path_
End With

Early-bound (requires reference to the Scripting library):

With New Scripting.FileSystemObject
    If Not .FolderExists(path_) Then .CreateFolder path_
End With

Upvotes: 4

Dave
Dave

Reputation: 4356

The following will work just fine:

Set myFolder = CreateObject("Scripting.FileSystemObject").GetFolder("C:\temp\")

WScript.Echo myFolder.Files.Count

Similarly, your example could be:

If CreateObject("Scripting.FileSystemObject").FolderExists("C:\Folder\") Then
    ' do something
End If

This will work fine as well.

You don't specifically need an object associated to the filesystemobject itself. If however you are using Option Explicit (and I can't think of a good reason not to), then declaring your variables before use is enforced.

Upvotes: 4

Related Questions