How to Check if File Exists Using VBA (With Example)


You can use the Dir function in VBA to check if a specific file exists in a specific folder.

Here is one common way to use this statement in practice:

Sub CheckFileExists()

'ask user to type path to file
InputFile = InputBox("Check if this file exists:")

'check if file exists and output results to message box
If Dir(InputFile) <> "" Then
    MsgBox "This File Exists"
Else
    MsgBox "This File Does Not Exist"
End If

End Sub

This particular macro will create an input box where the user can type a full path to a file to check if it exists.

Once the user enters the file path, the macro will then produce a message box that says whether or not the file exists.

The following example shows how to use this syntax in practice.

Example: Check if File Exists Using VBA

Suppose we have a folder located in the following location:

C:\Users\bob\Documents\current_data

This folder contains three CSV files:

Suppose we would like to use VBA to check if a file called soccer_data.csv exists in this folder.

We can create the following macro to do so:

Sub CheckFileExists()

'ask user to type path to file
InputFile = InputBox("Check if this file exists:")

'check if file exists and output results to message box
If Dir(InputFile) <> "" Then
    MsgBox "This File Exists"
Else
    MsgBox "This File Does Not Exist"
End If

End Sub

Once we run this macro, an input box appears where we can type in the file path:

VBA check if file exists

We will type in the full path to the soccer_data.csv file:

Once we click OK, a message box will appear that tells us if the file exists in the folder that we specified:

The message box tells us that the file does exist.

Note: You can find the complete documentation for the Dir function here.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

How to Create Folders Using VBA
How to Delete Folders Using VBA
How to Delete Files Using VBA

Leave a Reply

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