Check a File Exists
One of the most regular tasks I have to perform in VBA is working with other files. This is normally to copy data from or to put data into them. The most regular issue I face when doing this is the file is not where it should be, or where I expected it to be. This could be because I was given the wrong file path or someone moved or deleted it.
I put this function together so I could quickly and easily check if the file exists before trying to work on it.
To use it, you pass the file_path argument the file 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 file).
Function DoesFileExist(file_path As String) As Boolean ' Purpose --> Checks to see if a given file exists or not. If it ' it exists TRUE is returned, if not FALSE is returned. ' Arguments --> file_path (String) ' - Holds the path to the file to check. ' Returns --> (Boolean) ' - Returns FALSE by default ' - Returns TRUE only if the given file exists ' Created by --> Carl Nixon, Excel-Expert.co.uk ' Set up variables ' ================ ' Holds if the file is found or not Dim result As Boolean ' Holds the name of the file found when looking for the file Dim found_file As String ' Set result to FALSE as a default result = False ' Check it is safe to continue ' ============================ ' No folder path given so exit If Trim(file_path) = "" Then GoTo Finished ' Check if file exists ' ==================== ' Search for the file using DIR found_file = Dir(file_path) ' If a file was found set the result to true If found_file <> "" Then result = True ' Finish up ' ========= Finished: ' Return the result DoesFileExist = result End Function
All of the code featured on this site is available to download on my GitGub page. Click here to visit it.