How to check if a file exists using VBA?

To check if a file exists using VBA, you can utilize the Dir function to search the file system for the file. This function returns an empty string if the file is not found. To use the Dir function, you must provide the full path of the file including the file name and extension. If the file is found, the Dir function returns the file name and extension of the file. It is important to note that the Dir function is case-sensitive and will return an empty string if the case of the file name does not match the provided name.


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:UsersbobDocumentscurrent_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 .

x