In this post, you’ll learn how you can check if the file or folder exists with in your hard-disk using Excel VBA.
How to Check if File Exists in Excel VBA?
To check if the file exists on your computer using Excel VBA, you can use the DIR command. Below is a code snippet demonstrating the same.
Sub IsFileExists ()
Dim inputFileName As String
Dim outputFileName As String
inputFileName = "C:\DeveloperPublishFile.xlsx"
outputFileName = Dir(inputFileName)
If outputFileName = "" Then
MsgBox "The file doesnot exist"
Else
MsgBox "The file exists"
End If
End SubHow to Check if Folder Exists in Excel VBA?
You can use the Dir function to check if the folder exists in Excel VBA as well. Below is a code snippet demonstrating how this is done.
Sub IsFolderExists ()
Dim inputFileName As String
Dim outputFolderName As String
inputFileName = "C:\DeveloperPublishFolder"
outputFolderName = Dir(inputFileName,vbDirectory)
If outputFolderName = "" Then
MsgBox "The folder doesnot exist"
Else
MsgBox "The folder exists"
End If
End Sub