Vba excel if exists file

Sub test()

thesentence = InputBox("Type the filename with full extension", "Raw Data File")

Range("A1").Value = thesentence

If Dir("thesentence") <> "" Then
    MsgBox "File exists."
Else
    MsgBox "File doesn't exist."
End If

End Sub

In this when i pickup the text value from the input box, it doesn’t work. If however, if remove "the sentence" from If Dir() and replace it with an actual name in the code, it works. Can somebody help?

vba_user111's user avatar

asked Jul 20, 2012 at 6:25

Dinesh Goel's user avatar

Note your code contains Dir("thesentence") which should be Dir(thesentence).

Change your code to this

Sub test()

thesentence = InputBox("Type the filename with full extension", "Raw Data File")

Range("A1").Value = thesentence

If Dir(thesentence) <> "" Then
    MsgBox "File exists."
Else
    MsgBox "File doesn't exist."
End If

End Sub

answered Jul 20, 2012 at 6:31

Cylian's user avatar

CylianCylian

10.8k4 gold badges43 silver badges55 bronze badges

4

Use the Office FileDialog object to have the user pick a file from the filesystem. Add a reference in your VB project or in the VBA editor to Microsoft Office Library and look in the help. This is much better than having people enter full paths.

Here is an example using msoFileDialogFilePicker to allow the user to choose multiple files. You could also use msoFileDialogOpen.

'Note: this is Excel VBA code
Public Sub LogReader()
    Dim Pos As Long
    Dim Dialog As Office.FileDialog
    Set Dialog = Application.FileDialog(msoFileDialogFilePicker)

    With Dialog
        .AllowMultiSelect = True
        .ButtonName = "C&onvert"
        .Filters.Clear
        .Filters.Add "Log Files", "*.log", 1
        .Title = "Convert Logs to Excel Files"
        .InitialFileName = "C:InitialPath"
        .InitialView = msoFileDialogViewList

        If .Show Then
            For Pos = 1 To .SelectedItems.Count
                LogRead .SelectedItems.Item(Pos) ' process each file
            Next
        End If
    End With
End Sub

There are lots of options, so you’ll need to see the full help files to understand all that is possible. You could start with Office 2007 FileDialog object (of course, you’ll need to find the correct help for the version you’re using).

answered Jul 20, 2012 at 7:19

ErikE's user avatar

ErikEErikE

48.4k23 gold badges150 silver badges194 bronze badges

1

Correction to fileExists from @UberNubIsTrue :

Function fileExists(s_directory As String, s_fileName As String) As Boolean

  Dim obj_fso As Object, obj_dir As Object, obj_file As Object
  Dim ret As Boolean
   Set obj_fso = CreateObject("Scripting.FileSystemObject")
   Set obj_dir = obj_fso.GetFolder(s_directory)
   ret = False
   For Each obj_file In obj_dir.Files
     If obj_fso.fileExists(s_directory & "" & s_fileName) = True Then
        ret = True
        Exit For
      End If
   Next

   Set obj_fso = Nothing
   Set obj_dir = Nothing
   fileExists = ret

 End Function

EDIT: shortened version

' Check if a file exists
Function fileExists(s_directory As String, s_fileName As String) As Boolean

    Dim obj_fso As Object

    Set obj_fso = CreateObject("Scripting.FileSystemObject")
    fileExists = obj_fso.fileExists(s_directory & "" & s_fileName)

End Function

answered May 29, 2013 at 19:14

amackay11's user avatar

amackay11amackay11

7191 gold badge10 silver badges17 bronze badges

3

just get rid of those speech marks

Sub test()

Dim thesentence As String

thesentence = InputBox("Type the filename with full extension", "Raw Data File")

Range("A1").Value = thesentence

If Dir(thesentence) <> "" Then
    MsgBox "File exists."
Else
    MsgBox "File doesn't exist."
End If

End Sub

This is the one I like:

Option Explicit

Enum IsFileOpenStatus
    ExistsAndClosedOrReadOnly = 0
    ExistsAndOpenSoBlocked = 1
    NotExists = 2
End Enum


Function IsFileReadOnlyOpen(FileName As String) As IsFileOpenStatus

With New FileSystemObject
    If Not .FileExists(FileName) Then
        IsFileReadOnlyOpen = 2  '  NotExists = 2
        Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
    End If
End With

Dim iFilenum As Long
Dim iErr As Long
On Error Resume Next
    iFilenum = FreeFile()
    Open FileName For Input Lock Read As #iFilenum
    Close iFilenum
    iErr = Err
On Error GoTo 0

Select Case iErr
    Case 0: IsFileReadOnlyOpen = 0 'ExistsAndClosedOrReadOnly = 0
    Case 70: IsFileReadOnlyOpen = 1 'ExistsAndOpenSoBlocked = 1
    Case Else: IsFileReadOnlyOpen = 1 'Error iErr
End Select

End Function    'IsFileReadOnlyOpen

answered Jul 21, 2012 at 13:52

whytheq's user avatar

whytheqwhytheq

34k64 gold badges170 silver badges265 bronze badges

4

Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function

Works very well, almost, at my site. If I call it with «» the empty string, Dir returns «connection.odc«!! Would be great if you guys could share your result.

Anyway, I do like this:

Function FileExists(fullFileName As String) As Boolean
  If fullFileName = "" Then
    FileExists = False
  Else
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
  End If
End Function

answered Oct 22, 2015 at 11:12

Joachim Brolin's user avatar

1

Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function

answered Jun 14, 2015 at 2:09

Ronnie Royston's user avatar

Ronnie RoystonRonnie Royston

16k6 gold badges73 silver badges88 bronze badges

0

I’m not certain what’s wrong with your code specifically, but I use this function I found online (URL in the comments) for checking if a file exists:

Private Function File_Exists(ByVal sPathName As String, Optional Directory As Boolean) As Boolean
    'Code from internet: http://vbadud.blogspot.com/2007/04/vba-function-to-check-file-existence.html
    'Returns True if the passed sPathName exist
    'Otherwise returns False
    On Error Resume Next
    If sPathName <> "" Then

        If IsMissing(Directory) Or Directory = False Then

            File_Exists = (Dir$(sPathName) <> "")
        Else

            File_Exists = (Dir$(sPathName, vbDirectory) <> "")
        End If

    End If
End Function

answered Jul 20, 2012 at 6:31

Dan's user avatar

DanDan

44.9k17 gold badges88 silver badges157 bronze badges

2

Very old post, but since it helped me after I made some modifications, I thought I’d share. If you’re checking to see if a directory exists, you’ll want to add the vbDirectory argument to the Dir function, otherwise you’ll return 0 each time. (Edit: this was in response to Roy’s answer, but I accidentally made it a regular answer.)

Private Function FileExists(fullFileName As String) As Boolean
    FileExists = Len(Dir(fullFileName, vbDirectory)) > 0
End Function

answered Dec 19, 2018 at 3:55

Word Nerd's user avatar

based on other answers here I’d like to share my one-liners that should work for dirs and files:

  • Len(Dir(path)) > 0 or Or Len(Dir(path, vbDirectory)) > 0  'version 1 - ... <> "" should be more inefficient generally
    
    • (just Len(Dir(path)) did not work for directories (Excel 2010 / Win7))
  • CreateObject("Scripting.FileSystemObject").FileExists(path)  'version 2 - could be faster sometimes, but only works for files (tested on Excel 2010/Win7)
    

as PathExists(path) function:

Public Function PathExists(path As String) As Boolean
    PathExists = Len(Dir(path)) > 0 Or Len(Dir(path, vbDirectory)) > 0
End Function

answered Aug 12, 2019 at 9:21

Andreas Covidiot's user avatar

Andreas CovidiotAndreas Covidiot

4,1785 gold badges50 silver badges95 bronze badges

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!

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.

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 &amp; &quot;Sample.xls&quot;
'OR
'&quot;C:Sample.xls&quot; 'You can change this Loaction

Set FSO = CreateObject(&quot;Scripting.FileSystemObject&quot;)

If Not FSO.FileExists(sFile) Then
    MsgBox &quot;Specified File Not Found&quot;, vbInformation, &quot;Not Found&quot;
Else
    MsgBox &quot;Specified File Exists&quot;, vbInformation, &quot;Exists&quot;
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 &amp; &quot;Sample.xls&quot;  'You can change this location

    If Dir(stFileName) &lt;&gt; &quot;&quot; Then
        MsgBox &quot;Specified File Exists&quot;, vbInformation, &quot;Exists&quot;
    Else
         MsgBox &quot;Specified File Not Found&quot;, vbInformation, &quot;Not Found&quot;
    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

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

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

Like this post? Please share to your friends:
  • Vba excel find and select
  • Vba excel find all cells
  • Vba excel filtered rows
  • Vba excel filedialog filters add
  • Vba excel file in folder