To check if a file exists or not using VBA Excel.
In this VBA excel automation, for demonstration purpose we have placed a sample file in source folder, and then by VBA excel code we are checking if that file exists or not. We can see in the image below that we had a file called “SampleFile1.docx”. Below shown VBA code is written to check that if “SampleFile1.docx” exists at the path mentioned in the variable “SourceFile”.
Here we have used “FileExists” method of FileSystemObject object. If file exists, then we shall display the result in the message box.
Sub CheckFileExists() Dim objFileSystem As Object Dim SourceFile As String Set objFileSystem = CreateObject("Scripting.FileSystemObject") 'Path of source file SourceFile = "C:\Users\username\Desktop\macro\Final\New\MyFolder\SampleFile1.docx" 'Check if a file exists If objFileSystem.FileExists(SourceFile) = True Then MsgBox "Source file exists" Else MsgBox "Source file does not exist" End If Set objFileSystem = Nothing End Sub
If file exists then a message box will be displayed as shown below.
- We can also use Dir function to check if file exists
Post you may like