VBA Code to Check if Folder Exist

VBA Code to Check if Folder Exist

Validation is one of the important parts of any programming language. As per few studies, 60% of the code is focused on validating input or output.

In this article, we will explain 2 methods to validate if the given folder path is valid or not.

Method 1

Below VBA function uses Dir VBA function to validate Folder Path.

VBA Code to Check if Folder Exist
'This function checks if given folder path is valid or not
Public Function CheckFolderExist(strFolderPath As String) As Boolean

    'If Dir retunrs blank then it is invalid folder path
    If Dir(strFolderPath, vbDirectory) = "" Then
        CheckFolderExist = False
        MsgBox "Invalid Folder Path!", vbCritical
    'Else it is a valid folder path
    Else
        CheckFolderExist = True
        MsgBox "Valid Folder Path!", vbInformation
    End If
    
End Function

Explanation: If the function returns True then it is a valid folder path. If function returns False then it is invalid folder path.

Method 2

Below VBA function uses File System Object to validate Folder path

VBA Code to Check if Folder Exist
'This function checks if given folder path is valid or not
'Microsoft Scripting Runtime reference is required to run this code
Public Function CheckFolderExist(strFolderPath As String) As Boolean

    Dim objFileSystem As FileSystemObject
    
    Set objFileSystem = New FileSystemObject

    'If FolderExists function returns True then it is valid folder path
    If objFileSystem.FolderExists(strFolderPath) = True Then
        CheckFolderExist = True
        MsgBox "Valid Folder Path!", vbInformation
    'Else it is invalid folder path
    Else
        CheckFolderExist = False
        MsgBox "Invalid Folder Path!", vbCritical
    End If

End Function

Explanation: If the function returns True then it is a valid folder path. If function returns False then it is invalid folder path.

Read this post to know how you can add reference in Excel VBA

Read this post if to know how you can check if given file path is valid or not

Author:
Excelsirji.com was started with the thought of making people experience easy while working with Excel, data analytics, vba, automations etc.

Leave a Reply

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