The function that allows us to check if a file or folder exists is know as the DIR function. The syntax for the DIR function is as follows:
DIR [( path [, attributes ])]
The PATH argument is basically an address which returns the name of your file or folder. If the name is not found, DIR returns an empty string.
The ATTRIBUTES argument (which are optional) are listed in the below table.
ConstantVALUE | Value | Description |
---|---|---|
vbNormal | 0 | (Default) Files with no attributes |
vbReadOnly | 1 | Read-only files |
vbHidden | 2 | Hidden files |
vbSystem | 4 | System files |
vbDirectory | 16 | Directories or folders |
The default is vbNormal, which are files with no specific attributes. You can filter for files with a specific attribute by using the constants listed above.
An interesting thing you can use with the DIR function are wildcards. Wildcards represent “any characters” and are useful when you want to capture multiple items in a search based on a pattern of characters. There are two wildcard characters:
Asterisk (*) – This wildcard character will allow for any character(s) in any quantity.
Examples:
Exc* (any text starting with “Exc”)
*el (any text ending with “el”)
Exc*el (any text starting with “Exc”, ending with “el”, and any character in between)
Question Mark (?) – This wildcards character will allow for any character in a single character position
Examples:
??cel (The first and second characters can be anything, but the third through fifth characters must be “cel”)
Ex?el (The first and second characters must be “Ex”, the fourth and fifth characters must be “el”, but the third character can be anything)
Featured Course
Unlock Excel VBA & Excel Macros
Practical Examples
Task #1
We will use the DIR function to check if a file exists. If the file doesn’t exist, we will display a “File does not exist” message to the user. If the file exists, we will open the file.
Task #2
We will use the DIR function to check if a folder exists. If the folder doesn’t exist, we will prompt the user to ask if they would like to create that folder. If the responds with a “Yes”, we will create the folder for them.
Task #1 (Version 1) – Checking for the existence of a file
First, open the Visual Basic Editor (ALT-F11) and create an empty module (i.e. “LessonsFilesFolders”).
The DIR function returns a string, so we need to declare a variable named FileName to hold the returned value.
Dim FileName As String
The next step is to query a folder for a file and return the filename if it exists, or an empty string if the file does not exist. We will store the response in the FileName variable we created in the previous step.
FileName = VBA.FileSystem.Dir(“your folder name\your file name”)
In our example we will use the following code:
FileName = VBA.FileSystem.Dir(“C:\Users\LG\Desktop\VBA\S2_recordMacros_start.xlsx”)
If the file does not exist, the DIR function will return an empty string. We will test for the empty string response with an IF statement. If the file does not exist, we will display a message stating such. If the file does exist, this first version will simply show the filename in a message box.
If FileName = VBA.Constants.vbNullString Then
MsgBox "File does not exist."
Else
MsgBox FileName
End If
The completed code should look like the following:
Sub FileExists()
Dim FileName As String
FileName = VBA.FileSystem.Dir("C:\Users\LG\Desktop\VBA\S2_recordMacros_start.xlsx")
If FileName = VBA.Constants.vbNullString Then
MsgBox "File does not exist."
Else
MsgBox FileName
End If
End Sub
Execute the code by pressing F5 and observe the response.
This confirms that the file exists in the defined folder.
Task #1 (Version 2) – Checking for the existence of a file using wildcards
Alter the code to use wildcards when searching for the filename.
FileName = VBA.FileSystem.Dir("C:\Users\LG\Desktop\VBA\S2_*start.xls?)
We will also alter the code; instead of displaying a message, we will open the requested file.
Workbooks.Open "C:\Users\LG\Desktop\VBA\" & FileName
The updated code should appear as follows:
Sub FileExists()
Dim FileName As String
FileName = VBA.FileSystem.Dir("C:\Users\LG\Desktop\VBA\S2_*start.xls?")
If FileName = VBA.Constants.vbNullString Then
MsgBox "File does not exist."
Else
Workbooks.Open "C:\Users\LG\Desktop\VBA\" & FileName
End If
End Sub
Execute the code by pressing F5 and observe that the file opens.
Task #2 – Check if a folder exists
In this task, we will check to see if a folder exists. If the folder does not exist, we will prompt the user and ask if they would like to create the folder.
We will create two variables:
Path – Hold the full folder\filename information
Folder – Hold only the folder name
Dim Path as String
Dim Folder as String
We will set the Path variable to point to a folder that does not exist:
Path = “C:\Users\LG\Desktop\VBA\S12”
We will set the Folder variable to hold the folder location stored by the Path variable. Because this is a folder, we will use the optional constant vbDirectory in the DIR function.
Folder = Dir(Path,vbDirectory)
As we did earlier, we will check to see if the response returns an empty string. If the Folder variable contains an empty string, we will prompt the user to ask if they wish to create the folder.
We need to store the user’s response, so we will create a variable to hold the response.
Dim Answer as VbMsgBoxResult
If the folder does not exist, we will display a message and store the user’s response in the Answer variable.
Answer = MsgBox("Path does not exist. Would you like to create it?", vbYesNo, "Create Path?")
Now we will test the answer. We will use a Case statement to test the response.
If the user responds with “Yes”, we will create the folder. If the user responds with anything else, we will exit the subroutine.
Select Case Answer
Case vbYes
VBA.FileSystem.MkDir (Path)
Case Else
Exit Sub
End Select
If the folder does exist, we will inform the user of its existence with a message box response.
Else
MsgBox "Folder exists."
The completed code should look like the following:
Sub Path_Exists()
Dim Path As String
Dim Folder As String
Dim Answer As VbMsgBoxResult
Path = "C:\Users\LG\Desktop\VBA\S12"
Folder = Dir(Path, vbDirectory)
If Folder = vbNullString Then
Answer = MsgBox("Path does not exist. Would you like to create it?", vbYesNo, "Create Path?")
Select Case Answer
Case vbYes
VBA.FileSystem.MkDir (Path)
Case Else
Exit Sub
End Select
Else
MsgBox "Folder exists."
End If
End Sub
Execute the code by pressing F5. Because the folder does not exist, we are presented with the following message prompt.
If we answer “Yes”, the folder is created.
If we execute the macro a second time, we see the following response.
This is because the folder was created in the previous test.
Conclusion
We have demonstrated how you can use the DIR function to test whether a file or folder exists and decide what actions you wish to perform depending on the outcome of the test.
Practice Workbook
Feel free to Download the Workbook HERE.
Leila Gharani
I'm a 6x Microsoft MVP with over 15 years of experience implementing and professionals on Management Information Systems of different sizes and nature.
My background is Masters in Economics, Economist, Consultant, Oracle HFM Accounting Systems Expert, SAP BW Project Manager. My passion is teaching, experimenting and sharing. I am also addicted to learning and enjoy taking online courses on a variety of topics.