VBA Check Workbook Exists in Excel. When we are working with Workbooks, better to check Workbook exists or not before start working. If workbook doesn’t available we can check if any path is wrong or file name is wrong. We can correct it and continue work on it. To check whether file exists or not using Dir function in Excel VBA.
Here is the following syntax to Check Workbook Exists or Not using Dir Function in Excel VBA.
Dir([PathName],[Attributes As vbFileAttribute = vbNormal) As String
Where PathName and Attributes are optional arguments. It returns string type data.
Let us see the following example macro to Check Workbook Exists or Not in Excel VBA.
'VBA Check Workbook Exists in Excel Sub VBA_Check_Workbook_Exists() 'Variable declaration Dim sFilePath As String 'Value assigned to a variable sFilePath = "D:\FolderName\Sample.xlsx" 'Check Workbook exists or not If Dir(sFilePath) = "" Then 'Workbook is not available MsgBox "File doesn't exist.", vbCritical, "File is not available" Else 'Workbook is available MsgBox "File exists.", vbInformation, "File available" End If End Sub
Here is the output screenshot for above macro procedure.
Here are the instructions to use above macro procedure in Visual basic editor.
- Save Visual Basic Editor(VBE) by clicking Alt +F11
- Go to code window by clicking F7
- Copy above specified macro or procedure
- Paste above copied code in code window
- Run macro by clicking F5 or Run command
- You can see output on the screen
- Find above output screenshot of the specified procedure.
You may also like the related Workbook Object articles.