Determine if a workbook exists using VBA in Microsoft Excel

In Microsoft Excel, we can check if file exists at specific location using VBA code. The macro will display the status in the form of message box. In this article we will identify, if the status of any specific file exists or not, with the help of VBA code. We can use Dir function to check if file Exists in Location using Excel VBA.

Using this program we can check if there is any file that exists already in the same location. So, that we can delete or rename the old file.

 

Question: When we are creating macro to automate the task, we generally save the output file in a location. I would like to have a macro to verify & in return show the file is available or not at the specific path.

To illustrate this example we will save the “Sample.xlsx” file in the path "D:\FolderName\Sample.xlsx"

image 1

 

To identify if the workbook exists, we need to follow the below steps to launch VB editor:

  • Click on Developer tab
  • From Code group select Visual Basic

image 2

 

image 3

 

  • Click on Insert then Module
  • This will create new module
  • Enter the following code in the Standard Module

 

Sub FileExists()
    Dim FilePath As String
    Dim TestStr As String

    FilePath = "D:\FolderName\Sample.xlsx"

    TestStr = ""
    On Error Resume Next
    TestStr = Dir(FilePath)
    On Error GoTo 0
    If TestStr = "" Then
        MsgBox "File doesn't exist"
    Else
        Workbooks.Open "D:\FolderName\Sample.xlsx"
    End If
End Sub

 
image 4

 

  • Now the macro is all set to run, we will use F5 shortcut key & “Sample” file will open

image 5

 

  • If file is not available at the pre-defined path then the following message box will display

image 6

 

Conclusion: In this way we can easily recognize, if a particular file exists or not at specific path using VBA code.

 

image 48

 

If you liked our blogs, share it with your friends on Facebook. And also you can follow us on Twitter and Facebook.

We would love to hear from you, do let us know how we can improve, complement or innovate our work and make it better for you. Write us at info@exceltip.com

 
 

Leave a Reply

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

Terms and Conditions of use

The applications/code on this site are distributed as is and without warranties or liability. In no event shall the owner of the copyrights, or the authors of the applications/code be liable for any loss of profit, any problems or any damage resulting from the use or evaluation of the applications/code.