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!
Learn More!
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.
Published on: November 22, 2018
Last modified: February 20, 2023
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.
Check if file Exists in Location using Excel 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.
Instructions:
- Open an excel workbook
- Press Alt+F11 to open VBA Editor
- Insert a new module from Insert menu
- Copy the above code and Paste in the code window
- Press F5 to check the output
- You should see a message box as shown above
- Save the file as macro enabled workbook
Download Example File:
Please Download the following example file.
Analysistabs – Check if File Exists
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
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
-
Raman Goel
February 5, 2015 at 1:54 AM — ReplyHello,
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
-
PNRao
February 5, 2015 at 8:32 PM — Reply -
Raman Goel
February 5, 2015 at 10:14 PM — ReplyThank 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
-
Raman Goel
February 7, 2015 at 12:50 AM — ReplyThanks 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
-
Raman Goel
February 11, 2015 at 11:40 PM — ReplyThanks 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
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.
Page load link
Go to Top
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.
Step 2: Start the subprocedure.
Code:
Sub File_Example() End Sub
Step 3: Define the variable as String.
Code:
Sub File_Example() Dim FilePath As String End Sub
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
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
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
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
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
Step 9: Now run the macro to see the result.
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
Step 11: If I run the code now, it will return an empty string in the message box.
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
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.
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 –
- VBA Copy Paste
- VBA Web Scraping
- VBA Subscript out of Range
- VBA RGB
In VBA, you can check whether the file or a directory exists by using the Dir method. Look at the following Subroutine.
Sub fileOrDirectoryExists() Dim full_path As String full_path = «C:Excel1.png» MsgBox Dir(full_path) <> «» End Sub |
It will return the message True if the file exists.
But if you change
full_path = “C:Excel1.png”
to
full_path = “C:Excel “
It will also return True. You can modify the following code to return true only for files.
Sub fileExists() Dim full_path As String full_path = «C:Excel1.png» If Dir(full_path) <> «» Then If Right(full_path, 1) <> «« Then MsgBox True Else MsgBox False End If Else MsgBox False End If End Sub |
The code If Right(full_path, 1) <> “” Then will be executed only if the first character from the right is “”.
Check if a file exists with FileSystemObject
There is another better way to check whether the file exists. This time we are going to use FileSystemObject. It provides an easy way to access a computer’s file system.
The following code will work in a similar way as the last one.
Sub fileExistsFSO() Dim fso_obj As Object Dim full_path As String full_path = «C:Excel1.png» Set fso_obj = CreateObject(«Scripting.FileSystemObject») MsgBox fso_obj.fileExists(full_path) End Sub |
Check if files exist in a list
Let’s create a subroutine that will check a range of cells inside a worksheet and format. Cells will contain file paths to files.
But first, take a look at which files actually exist.
As you can see there are files from 1 to 10, with files 4, 5, and 6 missing. Take a look at our worksheet.
Select all cells from A1 to A12 and run the following code.
Sub fileExistsFSORange() Dim Rng As Range Set fso_obj = CreateObject(«Scripting.FileSystemObject») Set Rng = Selection For Each Cell In Rng If fso_obj.fileExists(Cell) Then Cell.Font.Color = vbGreen Else Cell.Font.Color = vbRed End If Next Cell End Sub |
All files that exist are green and the other files are read.
Check if the file exists function
So far we used subroutines. Let’s create a function that can be executed from the worksheet. Create a new module inside the current project and insert the following function.
Function FileExists(full_path As String) Dim fso_obj As Object Set fso_obj = CreateObject(«Scripting.FileSystemObject») FileExists = fso_obj.FileExists(full_path) End Function |
Now, if you start typing you will see a new function called FileExists.
Create the function for all the data on the worksheet.
As you can see it correctly returned TRUE and FALSE values whether the file exists or not.
Post Views: 9,856
VBA Check If File Exists If Not Create It in Excel. If not create a new file with specified name using VBA in Excel. We are using 2 methods to check folder exists or not. Those are Dir VBA function and FileSystemObject object. In the following tutorial let us see an example macro code. And also see the step by step instructions to run VBA code in the visual basic editor(VBE) window.
Table of Contents:
- Overview
- Example to Check If File Exists If Not Create It using VBA Dir Function
- VBA Checking If File Exists If Not Create It using FileSystemObject(FSO) Object
- Instructions to Run VBA Macro Code
- Other Useful Resources
Example to Check If File Exists using VBA Dir Function
Let us see an example macro to check specified file exists or not. If it is not available create a new file using VBA Dir function to check file exists or not. First we are checking specified folder is available or not. If file is not available then creates a new file. In this case we creates a new Workbook. You can create any file like ppt, word, CSV, Notepad etc.
'VBA Checking If File Exists If Not Create It using Dir Function Sub VBAF1_Check_If_File_Exists_If_Not_Create_It_Using_Dir_Function() 'Variable declaration Dim sFolderPath As String Dim sFileName As String, sFilePath As String 'Define Folder Path sFolderPath = "C:VBAF1Files and Folders" 'Specify File Name which we we are looking for sFileName = "Sample.xlsx" 'Create File Path sFilePath = sFolderPath & sFileName 'Check Specified Folder exists or not If Dir(sFilePath) <> "" Then 'Check file is available or not MsgBox "File already exists!", vbInformation, "VBAF1" Exit Sub End If 'If file is not available Dim Wb As Workbook 'Create New Workbook file Set Wb = Workbooks.Add 'Save File Wb.SaveAs sFolderPath & sFileName 'Close Workbook Wb.Close 'Display Message MsgBox "New file has created successfully!", vbInformation, "VBAF1" End Sub
Output: You can find output of the above macro code.
VBA Checking If File Exists If Not Create It using FileSystemObject(FSO) Object
Let us another example macro to check specified file exists or not. If it is not available create a new file using VBA FileSystemObject(FSO) to check file exists or not.
'VBA Check If File Exists If Not Create It Sub VBAF1_Check_If_File_Exists_If_Not_Create_It_Using_FSO() 'Variable declaration Dim sFolderPath As String Dim sFileName As String, oFile As Object, bStatus As Boolean 'Define Folder Path sFolderPath = "C:VBAF1Files and Folders" 'Specify File Name which we we are looking for sFileName = "Sample2.xlsx" 'Create FSO Object Set oFSO = CreateObject("Scripting.FileSystemObject") 'Check Specified Folder exists or not If oFSO.FolderExists(sFolderPath) Then 'Check Specified file exists or not If oFSO.FileExists(sFolderPath & sFileName) Then 'If file is available MsgBox "File already exists!", vbInformation, "VBAF1" Exit Sub End If End If 'If file is not available Dim Wb As Workbook 'Create New Workbook file Set Wb = Workbooks.Add 'Save File Wb.SaveAs sFolderPath & sFileName 'Close Workbook Wb.Close 'Display Message MsgBox "New file has created successfully!", vbInformation, "VBAF1" End Sub
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays VBA Text Files VBA Tables
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog