Check a Folder Exists
Over the years I have developed a lot of tools that iterate over files in a folder and import the data from each file, which is fairly straightforward. However, the number one cause of problems when doing this is the folder not being where you expect it to be. This could be because you were given the wrong folder path or somebody moved or deleted the folder.
I put this function together to check if the folder exists before I try to work on it.
To use it, you pass the folder_path argument the folder you want to check, and it will return TRUE or FALSE. If it returns FALSE I exit my programming in a controlled way (i.e. display an error message or ask the user to reselect the folder).
Function DoesFolderExist(folder_path As String) As Boolean ' Purpose --> Checks to see if a given folder path exists or not. If ' it exists TRUE is returned, if not FALSE is returned. ' Arguments --> folder_path (String) ' - Holds the path to the folder to check. If passed a file ' path including a filename, the filename will be ignored. ' Returns --> (Boolean) ' - Returns FALSE by default ' - Returns TRUE only if the given folder exists ' Created by --> Carl Nixon, Excel-Expert.co.uk ' Set up variables ' ================ ' Holds if the folder is found or not Dim result As Boolean ' Holds the name of the folder found when searching Dim found_folder As String ' Set result to FALSE as a default result = False ' Check its safe to continue ' ========================== ' If there is no folder path then exit If Trim(folder_path) = "" Then GoTo Finished ' Check folder exists ' =================== ' Search for the file using DIR found_folder = Dir(folder_path, vbDirectory) ' If a returned folder was found then set the result to true If found_folder <> "" Then result = True ' Finish up ' ========= Finished: ' Return the result DoesFolderExist = result End Function
All of the code featured on this site is available to download on my GitGub page. Click here to visit it.