Excel vba file there

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)

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 nameyour file name”)

In our example we will use the following code:

FileName = VBA.FileSystem.Dir(“C:UsersLGDesktopVBAS2_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:UsersLGDesktopVBAS2_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:UsersLGDesktopVBAS2_*start.xls?)

We will also alter the code; instead of displaying a message, we will open the requested file.

Workbooks.Open "C:UsersLGDesktopVBA" & FileName

The updated code should appear as follows:

Sub FileExists()
Dim FileName As String
    FileName = VBA.FileSystem.Dir("C:UsersLGDesktopVBAS2_*start.xls?")
    If FileName = VBA.Constants.vbNullString Then
        MsgBox "File does not exist."
    Else
        Workbooks.Open "C:UsersLGDesktopVBA" & 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 folderfilename 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:UsersLGDesktopVBAS12”

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:UsersLGDesktopVBAS12"
    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.

Excel Download Practice file

Published on: November 22, 2018

Last modified: February 20, 2023

Microsoft Most Valuable Professional

Leila Gharani

I’m a 5x 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.

Return to VBA Code Examples

VBA allows you to check if a file or folder exists by using the Dir function.

Using the Dir Command to Check If a File Exists

As we mentioned in the introduction, the Dir function allows us to check if a selected file exists on the computer. Here is the code:

Sub CheckFileExists ()

Dim strFileName As String
Dim strFileExists As String

    strFileName = "C:UsersNikolaDesktopVBA articlesTest File Exists.xlsx"
    strFileExists = Dir(strFileName)

   If strFileExists = "" Then
        MsgBox "The selected file doesn't exist"
    Else
        MsgBox "The selected file exists"
    End If

End Sub

We first assigned the file path to the variable strFileName. Then we use the Dir function to get the file name into the variable strFileExists. If the file exists in the directory, its name will be assigned to the string variable strFileExists.  If it does not exist then strFileExists will remain blank.  Finally, the message box appears informing us if the file exists or not.

Using the Dir Command to Check If a Folder Exists

Similarly to checking if a file exists, you can check if a folder exists. You just need to add one argument to the Dir command. Let’s look at the code:

Sub CheckFolderExists ()

Dim strFolderName As String
Dim strFolderExists As String

    strFolderName = "C:UsersNikolaDesktopVBA articlesTest Folder"
    strFolderExists = Dir(strFolderName, vbDirectory)

    If strFolderExists = "" Then
        MsgBox "The selected folder doesn't exist"
    Else
        MsgBox "The selected folder exists"
    End If

End Sub

We first assigned the folder path to the variable strFolderName. Then we use the Dir function to get the file name into the variable strFileExists. In order to check a folder, we need to add the second argument to the function – vbDirecotry. If the folder exists in the directory, its name will be assigned to the variable strFolderExists. If not strFolderExists will remain blank.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

VBA Check File Exists

Check File Exists Using Excel VBA

VBA Check File Exists helps to Check if file Exists in Location using Excel VBA. After mentioning the file path in the computer, what if someone deletes the file or change the folder path of the file? Obviously, our code will throw an error in such cases. To resolve this issue, we can do one thing before we actually open the file, we can check whether the mentioned file exists or not.

In this article, we will show you how to check whether the particular mentioned file exists or not.

How to Check if File Exists or Not?

  • How excel VBA knows whether the file exists or not??
  • By default, it cannot!!!
  • So, then how??
  • We need to use the function called “Dir” to check whether the file exists or not.

What does DIR Function Do?

VBA DIR function returns the name of the file name with its extension in the specified folder path. When the folder doesn’t have any file, it returns the empty string.

So by using this function, we can actually test whether the file exists or not. Even without the DIR function, we can test whether the file exists or not. We will see some of the examples below.

How to Use VBA Check File Exists in Excel?

We will learn how to use a VBA Check File Exists Function with few examples in excel.

You can download this VBA Check File Exists Excel Template here – VBA Check File Exists Excel Template

Example #1 – VBA Check File Exists

Ok, let’s write some code to test the file exists or not. Follow the below steps to write code on your own.

Step 1: For this, go to the VBA window and under the Insert menu select Module as shown below.

VBA Check File Exists Module

Step 2: Start the subprocedure.

Code:

Sub File_Example()

End Sub

VBA Check File Exits Example 1.1

Step 3: Define the variable as String.

Code:

Sub File_Example()

Dim FilePath As String

End Sub

VBA Check File Exits Example 1.2

Step 4: Now, I want to test the file named as “Chapter-11. InputBoxes.xlsm” in my E-Drive”. I will assign my file path to this variable.

Code:

Sub File_Example()

Dim FilePath As String

FilePath = "D:Test File.xlsx"

End Sub

 Example 1.4

Step 5: Now define one more variable to apply the DIR function.

Code:

Sub File_Example()

Dim FilePath As String
Dim FileExists As String

FilePath = "D:Test File.xlsx"

End Sub

Example 1.5

Step 6: Now, for the second variable, open the DIR function.

Code:

Sub File_Example()

Dim FilePath As String
Dim FileExists As String

FilePath = "D:Test File.xlsx"
FileExists = Dir(

End Sub

Example 1.7

Step 7: DIR function requires the file path. Since we have already assigned the file path to the variable “FilePath”, we can simply pass this variable to the DIR function.

Code:

Sub File_Example()

Dim FilePath As String
Dim FileExists As String

FilePath = "D:Test File.xlsx"
FileExists = Dir(FilePath)

End Sub

Example 1.8

Step 8: Now DIR function returns only the File Name as “Chapter-11. InputBoxes” from the mentioned file path. So let’s show the result in a message box.

Code:

Sub File_Example()

Dim FilePath As String
Dim FileExists As String

FilePath = "D:Test File.xlsx"
FileExists = Dir(FilePath)

MsgBox FileExits

End Sub

Example 1.9

Step 9: Now run the macro to see the result.

VBA Check File Exits 1

Since there is a file that exists in the mentioned path, our DIR function filtered the file name from the huge path.

Step 10: Now, I will change the file name to a different thing which is not there in the mentioned path.

Code:

Sub File_Example()

Dim FilePath As String
Dim FileExists As String

FilePath = "D: File.xlsx"
FileExists = Dir(FilePath)

MsgBox (FileExists)

End Sub

 Example 1.10

Step 11: If I run the code now, it will return an empty string in the message box.

Example 1.11

DIR function is best suited to use with the IF statement in VBA. Above, we could see only the file name with its extension if it exists, or else we could only see the empty string.

Example #2 – DIR with IF Condition

Step 1: But using the IF statement with the DIR function, we can alter our results. For an example, look at the below code.

Code:

Sub File_Example1()

Dim FilePath As String
Dim FileExists As String
FilePath = "C:Userscba_28DesktopAlexFinal Input.xlsm"

FileExists = Dir(FilePath)

     If FileExists = "" Then
MsgBox "File doesnt exists in the mentioned path"
     Else
MsgBox "File exists in the mentioned path"
End If

End Sub

VBA Check File Exits Example 2.1

Step 2: Here IF condition checks whether the variable “FileExists” value is nothing (“”) or not. If the variable value is nothing (“”), then it will return the result as “File doesn’t exist in the mentioned path”, or else it will return the result as “File exists in the mentioned path.”

Below is an example of a screenshot of the same.

VBA Check File Exits Example 2.2

Example 2.3

By using the DIR function, we can check whether the file exists or not.

Recommended Articles

This is a guide to VBA Check File Exists. Here we discuss how to use Excel VBA Check File Exists Function along with practical examples and a downloadable excel template. You can also go through our other suggested articles –

  1. VBA Copy Paste
  2. VBA Web Scraping
  3. VBA Subscript out of Range
  4. VBA RGB
Skip to content

Check if file Exists in Location using Excel VBA

Home » Excel VBA » Check if file Exists in Location using Excel VBA

  • Check if file exists Using VBA

VBA check if file exists example Excel Macro code helps to Check if file Exists in Location using Excel VBA. You can use FileSystemObject or Dir function to check if file Exists in Location using Excel VBA.

For example, When we are automating any task we generally save the output file in a location. Using this program we can check if there is any file exists already in the same location. So that we can delete or rename the old file.

  • Solution
  • Code
  • Output
  • Instructions
  • Example File

Solution(s):

You can use FileSystemObject or Dir function to check if file Exists in Location using Excel VBA.Follwoing are the examples to show you how to check If a file is already exists in a folder or not. Follwoing are the two different methods.

Check if file Exists in Location using Excel VBA – Example Cases:

  • Check if file Exists in Location using Excel VBA – Using FileSystemObjects
  • Check if file Exists in Location using Excel VBA – Using Dir Function
Check if file Exists in Location using Excel VBA – Using FileSystemObjects

Following is the example to check if a file exists in a folder with using FileExists function of FileSystemObject.

Code:
'In this Example I am checking if Sample.xls file which exists in the same location of the macro file
Sub sbCheckingIfFileExists()

Dim FSO
Dim sFile As String

sFile = ThisWorkbook.Path & "Sample.xls"
'OR
'"C:Sample.xls" 'You can change this Loaction

Set FSO = CreateObject("Scripting.FileSystemObject")

If Not FSO.FileExists(sFile) Then
    MsgBox "Specified File Not Found", vbInformation, "Not Found"
Else
    MsgBox "Specified File Exists", vbInformation, "Exists"
End If

End Sub
Check if file Exists in Location using Excel VBA – Using Dir Function

Following is the example to check if a file exists in a folder with using Dir function.

Code:
'In this Example I am checking if Sample.xls file which exists in the same location of the macro file
Sub Check_If_File_Exists()

    Dim stFileName As String

    stFileName = ThisWorkbook.Path & "Sample.xls"  'You can change this location

    If Dir(stFileName) <> "" Then
        MsgBox "Specified File Exists", vbInformation, "Exists"
    Else
         MsgBox "Specified File Not Found", vbInformation, "Not Found"
    End If

End Sub
Output:

If file exists in a location, it will show following message. Otherwise it will show “Specified File Not Found” message.
Check if file exists Using VBA

Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Insert a new module from Insert menu
  4. Copy the above code and Paste in the code window
  5. Press F5 to check the output
  6. You should see a message box as shown above
  7. Save the file as macro enabled workbook
Download Example File:

Please Download the following example file.
Analysistabs – Check if File Exists

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

    • Solution(s):
  • Check if file Exists in Location using Excel VBA – Example Cases:

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

5 Comments

  1. Raman Goel
    February 5, 2015 at 1:54 AM — Reply

    Hello,

    I like the above VBA coding and want to know if an macro can be created to see the list of files exist in some particular folder or not?
    and instead of msg box pop-up, it will just show it in one cell adjacent to the file name if it exist or not? If it can be done then it will resolve all my purpose. Please e-mail me at —- if you already have any sample macro for it.

    Thank you

  2. PNRao
    February 5, 2015 at 8:32 PM — Reply
  3. Raman Goel
    February 5, 2015 at 10:14 PM — Reply

    Thank you for the quick response!
    However, the link showed a Analysis of data and I need an macro to check for various files exist in particular folder or not. I am not sure if the same link can be modify for my need or not?

    Could you please help me and assist me if an macro can be created to check multiple files exist in the folder or not and instead of pop-up message box, it will show in excel columns only?

    Raman Goel

  4. Raman Goel
    February 7, 2015 at 12:50 AM — Reply

    Thanks Buddy,

    Analysis Tab is awesome, however it is not resolving my purpose completely. The tab is pulling the file names from the folder but I still need to check the names manually to find if anything missing.
    We save some same set of files each day in particular folder, so what I am asking is if through formula it is possible to check if file exist or not and will revert with “Yes” or “No” then it will be great.

    i am not very good at excel so it is difficult for me to frame the formula. Can you please assist me if possible?

    Raman Goel

  5. Raman Goel
    February 11, 2015 at 11:40 PM — Reply

    Thanks Buddy,
    Analysis Tab is awesome, however it is not resolving my purpose completely. The tab is pulling the file names from the folder but I still need to check the names manually to find if anything missing.
    We save some same set of files each day in particular folder, so what I am asking is if through formula it is possible to check if file exist or not and will revert with “Yes” or “No” then it will be great.
    i am not very good at excel so it is difficult for me to frame the formula. Can you please assist me if possible?
    Raman Goel

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

Home / VBA / VBA Check IF a Workbook Exists in a Folder (Excel File)

To check if a workbook exists in a specific folder, you can use the DIR function. DIR is a function that stands for the directory. You need to specify the path of the file along with the name and extension. If a file exists, it returns the file name, otherwise a blank value.

Write a Code to Check IF an Excel File Exists in a Folder

Use the following steps:

  1. First, specify a range or a message box to get the result of the function.
  2. Now, enter the function name “DIR” and type starting parentheses.
  3. After that, enter the path of the file using double quotation marks and make sure to enter the file extension along with the file name.
  4. Next, type the closing parentheses to close the line of code.
Sub vba_Check_workbook()
MsgBox Dir("C:UsersDellDesktopbook1.xlsx")
End Sub

When you run this line of code, it shows you a message box with the file name which means the file exists in the location that you have specified.

Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook

Check for Multiple Files IF Exist in a Folder

There could be a chance that you need to check for multiple files if they all exist in a folder. In that case, you can use the following code.

Sub vba_check_workbook()

Dim myFolder As String
Dim myFileName As String
Dim myRange As Range
Dim myCell As Range

Set myRange = Range("A1:A5")
myFolder = "C:UsersDellDesktopData"

For Each myCell In myRange
    myFileName = myCell.Value
    If Dir(myFolder & "" & myFileName) = "" Then
        myCell.Offset(0, 1) = "File Doesn't Exists."
    Else
        myCell.Offset(0, 1) = "File Exists"
    End If
Next myCell

End Sub

To understand this code, I have broken it into three parts.

  • In the FIRST part, you have all the variables that we need to use in the code. A variable to use as the folder address, file name, the range where you have all the names, and each cell of the range.
  • In the SECOND part, you have defined the range address where you have all the names of the files that you wish to check. And also the assigned folder path to the variable.
  • In the THIRD part, you have a FOR EACH LOOP to loop through all the files in the folder. This loop uses the DIR to match all the names that you have in the range. It also uses IF STATEMENT to enter a value to the corresponding cell as a remark if the file exists or not.

Note: If you want to use this code, you need to change the folder path in the, and you need to define the range where you have all the names of the workbooks.

More on VBA Workbooks

VBA Save Workbook | VBA Close Workbook | VBA Delete Workbook | VBA ThisWorkbook | VBA Rename Workbook | VBA Activate Workbook | VBA Combine Workbook | VBA Protect Workbook (Unprotect) | VBA Check IF a Workbook is Open | VBA Open Workbook | VBA Create New Workbook (Excel File)

  • VBA Workbook

Like this post? Please share to your friends:
  • Excel vba file not saved
  • Excel vba file not found
  • Excel vba file get
  • Excel vba exportasfixedformat from to
  • Excel vba export to pdf