RSS

How to check if a directory/folder exists

If you are reading or writing files with VBA macros, it will be necessary to check if a certain directory (folder) exists, or you might get an error. There is more than one way to do this, and below are two examples (functions).

When they are called, the folder name and path are passed as a String, and the functions return TRUE or FALSE, if the folder exists or not.


Public Function DirCheck(ByVal sDirPath As String) As Boolean
'Returns TRUE if a directory exists.

On Error GoTo ErrorHandle

'If the path is less than 2 characters, we leave.
If Len(sDirPath) < 2 Then
   DirCheck = False
   Exit Funtion
End If

If Len(Dir(sDirPath, vbDirectory)) > 0 Then
   DirCheck = True
   DirCheck = False
End If

Exit Function
ErrorHandle:
MsgBox Err.Description & ", error in function DirCheck."
End Function

Public Function ValidDir(ByVal sPath As String) As Boolean
'Returns TRUE if a directory exists.
'Works only in Excel >= 2000.
Dim fsObject

On Error GoTo ErrorHandle

Set fsObject = CreateObject("Scripting.FileSystemObject")
If fsObject.folderExists(sPath) = True Then ValidDir = True

BeforeExit:
Set fsObject = Nothing
Exit Function
ErrorHandle:
MsgBox Err.Description & ", error in function ValidDir"
Resume BeforeExit
End Function

Related: