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

 

Published by

Dinesh Kumar Takyar

Welcome to exceltrainingvideos.com! My aim is to help you learn MS Excel including VBA. I always felt that a good way to learn something was to find solutions to problems in that domain. That is why I share these Excel videos with you. Mostly these are questions asked during my corporate training sessions. I've been training individuals and companies in computers since 1991. I did my B. Sc. (Vordiplom), M. Sc. (Diplom) and Ph.D. (Dr. rer. nat.) from Hamburg, Germany. The best thing about solving some of my visitor's questions is that I also gain new insights. For more Excel VBA solutions you may like to visit my YouTube channel: http://youtube.com/familycomputerclub For a structured Excel VBA training course online you can visit: https://www.youtube.com/excelvbaonline

Leave a Reply

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