VBA – Determine if a Folder/Directory Exists or Not

Icon of a Folder with a Check-mark on it

It can often come handy to be able to quickly determine if a Folder/Directory exists or not (especially before trying to use it for something!). Below are a few possible approaches that can be employed to check the existence of a folder/directory using VBA:

I have recently updated them to include an optional parameter to create the folder should it not be found.

Using The VBA Dir Function

'---------------------------------------------------------------------------------------
' Procedure : FolderExist
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Test for the existence of a Folder/Directory
'             True  => Folder exists
'             False => Folder does not exist
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: None required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFolder   : Full path of the folder to be tested for
' bCreateIt : (True/False) whether it should be created if it is not found
'
' Usage:
' ~~~~~~
' Call FolderExist("C:\Test\")
' Call FolderExist("C:\Test\Me\", True)
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2009-10-02              Initial Release
' 2         2018-02-01              Updated Copyright under CC licensing
'                                   Added bCreateIt to create it if not found
'---------------------------------------------------------------------------------------
Function FolderExist(sFolder As String, Optional bCreateIt As Boolean = False) As Boolean
On Error GoTo Error_Handler
 
    If sFolder = vbNullString Then GoTo Error_Handler_Exit
    If Dir(sFolder, vbDirectory) <> vbNullString Then
        FolderExist = True
    End If
    
    If FolderExist = False And bCreateIt = True Then
        MkDir sFolder
    End If
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    If Err.Number <> 52 Then
        MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: FolderExist" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    End If
    Resume Error_Handler_Exit
End Function

 

Using The File System Object’s FolderExists Method

'---------------------------------------------------------------------------------------
' Procedure : FSO_FolderExist
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Test for the existence of a Folder/Directory
'             True  => Folder exists
'             False => Folder does not exist
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Late Binding  -> None required
'             Early Binding -> Microsoft Scripting Runtime
' References: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/folderexists-method
'             https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/createfolder-method
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFolder   : Full path of the folder to be tested for
' bCreateIt : (True/False) whether it should be created if it is not found
' bRevalidateAfterCreation : (True/False) Should validation of the existence of the
'                               folder be done after the creation process
'
' Usage:
' ~~~~~~
' FSO_FolderExist("C:\Temp")
'   Returns -> True/False
'
' FSO_FolderExist("C:\Temp", True)
'   Returns -> True/False, If False will create it, but returns False
'
' FSO_FolderExist("C:\Temp", True, True)
'   Returns -> True/False, If False will create it, and should return True if
'                          all was successful
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2009-10-02              Initial Release
' 2         2018-02-01              Updated Copyright under CC licensing
'                                   Added bCreateIt to create it if not found
' 3         2019-08-22              Added bRevalidateAfterCreation
' 4         2024-02-01              Public Release
'---------------------------------------------------------------------------------------
Function FSO_FolderExist(ByVal sFolder As String, _
                         Optional bCreateIt As Boolean = False, _
                         Optional bRevalidateAfterCreation As Boolean = False) As Boolean
    On Error GoTo Error_Handler
    #Const FSO_EarlyBind = False 'True = Early Binding, False = Late Binding

    #If FSO_EarlyBind = True Then
        Dim oFSO              As Scripting.FileSystemObject
        Set oFSO = New FileSystemObject
    #Else
        Dim oFSO              As Object
        Set oFSO = CreateObject("Scripting.FileSystemObject")
    #End If

    FSO_FolderExist = oFSO.FolderExists(sFolder)

    If Not FSO_FolderExist And bCreateIt Then
        oFSO.CreateFolder (sFolder)
        'or MkDir sFolder
        
        If bRevalidateAfterCreation Then
            DoEvents
            FSO_FolderExist = oFSO.FolderExists(sFolder)
        End If
    End If

Error_Handler_Exit:
    On Error Resume Next
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Source: FSO_FolderExist" & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has occurred!"
    Resume Error_Handler_Exit
End Function

 

GetAttr

'---------------------------------------------------------------------------------------
' Procedure : GA_FolderExist
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Test for the existence of a folder; Returns True/False
'               True  => File exists
'               False => File does not exist
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: None required
' References: https://learn.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/getattr-function
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFolder     : Full path of the folder to be tested for
'
' Usage:
' ~~~~~~
' GA_FolderExist("C:\Temp\")
'   Returns -> True/False
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2024-02-02
'---------------------------------------------------------------------------------------
Function GA_FolderExist(ByVal sFolder As String) As Boolean
On Error GoTo Error_Handler
    Dim iRetVal               As Integer

    iRetVal = GetAttr(sFolder)
    GA_FolderExist = (iRetVal And vbDirectory)
 
Error_Handler_Exit:
    On Error Resume Next
    Exit Function
 
Error_Handler:
    'We're here because nothing was found
    Resume Error_Handler_Exit
End Function

 

GetFileAttributes

Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long

'---------------------------------------------------------------------------------------
' Procedure : API_FileAttributes
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Test for the existence of a file or folder; Returns True/False
'               True  => File/Folder exists
'               False => File/Folder does not exist
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd:      FindFirstFile API and Type/Const Declarations
' References: https://learn.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/getattr-function
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFile     : Full path of the folder to be tested for
'
' Usage:
' ~~~~~~
' API_FileAttributes("C:\Temp\") 'Check for a Folder
'   Returns -> True/False
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2024-02-02              Initial Release
'---------------------------------------------------------------------------------------
Function API_FileAttributes(ByVal sFolder As String) As Boolean
    On Error GoTo Error_Handler
    Dim lRetVal               As Long
    Const FILE_ATTRIBUTE_DIRECTORY = &H10

    lRetVal = GetFileAttributes(sFolder) '-1 seems to indicate invalid
    If (lRetVal Or FILE_ATTRIBUTE_DIRECTORY) > 0 Then API_FileAttributes = True

Error_Handler_Exit:
    On Error Resume Next
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Source: API_PathFileExist" & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

 

PathFileExists

Public Declare Function PathFileExists Lib "SHLWAPI.DLL" Alias "PathFileExistsA" (ByVal pszPath As String) As Long


'---------------------------------------------------------------------------------------
' Procedure : API_PathFileExist
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Test for the existence of a file or folder; Returns True/False
'               True  => File/Folder exists
'               False => File/Folder does not exist
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd:      FindFirstFile API and Type/Const Declarations
' References: https://learn.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/getattr-function
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFile     : Full path of the folder to be tested for
'
' Usage:
' ~~~~~~
' API_PathFileExist("C:\Temp\Flow-Undo-Dont.jpg") 'Check for a File
'   Returns -> True/False
'
' API_PathFileExist("C:\Temp\") 'Check for a Folder
'   Returns -> True/False
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2024-02-02              Initial Release
'---------------------------------------------------------------------------------------
Function API_PathFileExist(ByVal sFolder As String) As Boolean
    On Error GoTo Error_Handler

    API_PathFileExist = (PathFileExists(sFolder) = 1)

Error_Handler_Exit:
    On Error Resume Next
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Source: API_PathFileExist" & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function
If API_PathFileExist("C:\Temp\") Then
    Debug.Print "Folder Exists"
Else
    Debug.Print "Folder Does NOT Exists"
End If

 

Windows Management Instrumentation

'---------------------------------------------------------------------------------------
' Procedure : WMI_FolderExist
' Author    : Daniel Pineault, CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Test for the existence of a folder; Returns True/False
'               True  => File exists
'               False => File does not exist
' Copyright : The following is release as Attribution-ShareAlike 4.0 International
'             (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-sa/4.0/
' Req'd Refs: Early Binding -> Microsoft WMI Scripting VX.X Library
'             Late Binding  -> None required
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFolder     : Full path of the folder to be tested for
'
' Usage:
' ~~~~~~
' WMI_FolderExist("C:\Temp\")
'   Returns -> True/False
'
' Revision History:
' Rev       Date(yyyy-mm-dd)        Description
' **************************************************************************************
' 1         2024-02-02
'---------------------------------------------------------------------------------------
Public Function WMI_FolderExist(ByVal sFolder As String) As Boolean
    On Error GoTo Error_Handler
    #Const WMI_EarlyBind = False    'True => Early Binding / False => Late Binding
    #If WMI_EarlyBind = True Then
        Dim oWMI              As WbemScripting.SWbemServices
        Dim oCols             As WbemScripting.SWbemObjectSet
    #Else
        Dim oWMI              As Object
        Dim oCols             As Object
    #End If
    Dim sWMIQuery             As String         'WMI Query

    If Right(sFolder, 1) = "\" Then sFolder = Left(sFolder, Len(sFolder) - 1)
    sFolder = Replace(sFolder, "\", "\\")    'Escape \ character!

    Set oWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
    sWMIQuery = "Select * From Win32_Directory Where Name = '" & sFolder & "'"
    Set oCols = oWMI.ExecQuery(sWMIQuery)
    WMI_FolderExist = (oCols.Count <> 0)

Error_Handler_Exit:
    On Error Resume Next
    Set oCols = Nothing
    Set oWMI = Nothing
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: WMI_FolderExist" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

 

Speed Comparison

  Dir FSO FSO (SHOV) GetAttr GetFileAttributes PathFileExist WMI
Average Execution Time 0.00005449 0.00004242 0.00003078 0.00002909 0.00002791 0.00003131 0.0071592400
% Diff vs GetFileAttributes 64.51% 41.26% 9.78% 4.14% 0.0% 11.48% 198.45%

 

Alternate Strategy

I’ll end by mentioning that some, instead of testing and then creating the folder if it is missing, simply run the folder creation routine, never testing beforehand. They simply skip that step. Depending on the environment, security settings, … this can be a viable option. Is it better, more efficient? We’d have to do so testing! But one more idea to ponder.

If you want to explore folder structure creation, be sure to check out my article on the subject:

 

Useful Resources

 

Page History

Date Summary of Changes
2011-09-16 Initial Release
2018-02-01 Updated Function Header
2024-02-01 Added FSO Approach
2024-02-03 Added GetAttr Approach
Added GetFileAttributes Approach
Added PathFileExists Approach
Added WMI Approach

3 responses on “VBA – Determine if a Folder/Directory Exists or Not

  1. Stephan Hodges

    Note that your code is showing “&” instead of “&”.

    Similarly for other values, such as “”, etc.

    1. admin Post author

      Thank you for pointing that out. I installed a plug-in into my website that completely messed my code up. I thought I had cleaned up all the problem, but obviously I missed this one.

  2. Michael Nickel

    Thanks a lot!!! That’s what I was looking for! A directory-check and creation if failed without this unsafe fso!!! It works reliably (Windows 10, Word 2010). Thumbs up!