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”
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
- 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
- Now the macro is all set to run, we will use F5 shortcut key & “Sample” file will open
- If file is not available at the pre-defined path then the following message box will display
Conclusion: In this way we can easily recognize, if a particular file exists or not at specific path using VBA code.
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 firstname.lastname@example.org