Home » excel » Excel VBA – Function to detect if a file exists based on Cell Values

Excel VBA – Function to detect if a file exists based on Cell Values

Posted by: admin May 14, 2020 Leave a comment

Questions:

Trying to write a function to detect if a file (pdf) exists. Due to there being a number of files/folders I’d like to build the filepath from cell values.

I’ve got this so far:

Public Function FileExists(FullpathName As String) As Boolean

If Len(Dir(FullpathName)) = 0 Then

    FileExists = True

Else

    FileExists = False

End If

End Function

And I’m entering this in the cell:

=FileExists(A2&B2&A3&" "&A1&" "&C2&".pdf")

but it’s returning it as false when the file is definitely in there. Can anyone shed some light on what I’m missing?

Thankyou!

How to&Answers:

Your IF condition is backwards, use:

Public Function FileExists(FullpathName As String) As Boolean
    If Len(Dir(FullpathName)) = 0 Then
        FileExists = False
    Else
        FileExists = True
    End If
End Function