Check if file exists in VBA Excel- debugvba.com

check if file exists VBA Excel

Objective

To check if a file exists or not using VBA Excel.

Approach

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”.

check if file exists VBA Excel

Code

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.

 

check if file exists VBA Excel


Note

  1. We can also use Dir function to check if file exists

Reference

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/fileexists-method

Post you may like

Check if a worksheet exists or not in VBA Excel