Check If Folder Exists with VBA

We may need to check if a folder exists in our computer’s hard disk. We can check for a folder’s existence in our computer quickly and easily with VBA. Either we use the DIR function or the File System Object (FSO)┬áto verify the existence of a folder. If a folder is empty or does not have any files in it, the DIR function informs us that the folder does not exist. If a folder has files in it, the DIR function works fine. Using the FSO method in our VBA code we can check for all types of folders – empty or not. Watch the training video before studying the VBA code:

Watch this video on YouTube.

The complete VBA code to check for the existence of a folder using DIR function:

Sub test_If_Folder_Exists_Using_Dir()
Dim Path As String
Dim TestStr As String

Path = “C:\Misc”
If Right(Path, 1) <> “\” Then
Path = Path & “\”
End If

TestStr = “”
TestStr = Dir(Path)
If TestStr = “” Then
MsgBox “Folder does not exist!”
Else
MsgBox “Folder exists!”
End If
End Sub

VBA code using FSO or File System Object to check if a folder exists:

Sub test_If_Folder_exists_Using_FSO()
Dim FSO As Object
Dim Path As String
Set FSO = CreateObject(“scripting.filesystemobject”)
Path = “C:\Misc”
If Right(Path, 1) <> “\” Then
Path = Path & “\”
End If
If FSO.FolderExists(Path) = False Then
MsgBox “Folder does not exist!”
Else
MsgBox “Folder exists!”
End If

End Sub

Further reading

Test if Folder, File or Sheet exists or File is open

 

Leave a Reply

Your email address will not be published. Required fields are marked *