Chris Spalton
Chris Spalton

Reputation: 143

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

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!

Upvotes: 1

Views: 4392

Answers (1)

Gary's Student
Gary's Student

Reputation: 96791

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

Upvotes: 3

Related Questions