Monday, April 30, 2007

VBA Function to Check File Existence

This Visual Basic Function can be used to check if a file exists under a specific directory

Sub Check_If_File_Exists()

' To Check if a file is present, give the file name and omit the second argument
sFile = "c:\Temp\Test.txt"
If File_Exists(sFile) = True Then
MsgBox sFile & " exist"
Else
MsgBox sFile & " does not exist"
End If

' To Check if a directory is present, give the directory name and make the second argument = True
sDir = "d:\VBADudExamples\Code"
If File_Exists(sDir, True) = True Then
MsgBox "Directory " & sDir & " exist"
Else
MsgBox "Directory " & sDir & " does not exist"
End If


End Sub
' Keywords : Check Directory Existence, VBA Dir Function, Visual Basic Dir Function, Dir$ Function Example, VB File Exists, VBA Check File Availability


Private Function File_Exists(ByVal sPathName As String, Optional Directory As Boolean) As Boolean

'Returns True if the passed sPathName exist
'Otherwise returns False
On Error Resume Next
If sPathName <> "" Then

If IsMissing(Directory) Or Directory = False Then

File_Exists = (Dir$(sPathName) <> "")
Else

File_Exists = (Dir$(sPathName, vbDirectory) <> "")
End If

End If
End Function

BlogRankings.com

All-Blogs.net directory

8 comments:

  1. Anonymous10:59 AM

    It's a very useful function in VBA. Thanks.

    ReplyDelete
  2. Anonymous2:51 PM

    Here is an other solution based on the same coding logic!

    http://vbaexcel.eu/vba-macro-code/determine-if-file-or-directory-exists

    ReplyDelete
  3. It's telling me the function File_Exists does not exist.

    ReplyDelete
  4. It's telling me the function File_Exists does not exist

    ReplyDelete
    Replies
    1. Anonymous12:46 PM

      !cause U HAVE to paste ths n workbook or wherever u using da code:!

      Private Function File_Exists(ByVal sPathName As String, Optional Directory As Boolean) As Boolean

      'Returns True if the passed sPathName exist
      'Otherwise returns False
      On Error Resume Next
      If sPathName <> "" Then

      If IsMissing(Directory) Or Directory = False Then

      File_Exists = (Dir$(sPathName) <> "")
      Else

      File_Exists = (Dir$(sPathName, vbDirectory) <> "")
      End If

      End If
      End Function

      Delete
    2. Anonymous11:49 AM

      just change private to public

      Delete
  5. i haven't used access 2007 but in 2003 i use FileExists instead of File_Exists

    ReplyDelete
  6. http://allenbrowne.com/func-11.html

    ReplyDelete

StumbleUpon
Share on Facebook
Related Posts Plugin for WordPress, Blogger...
Download Windows Live Toolbar and personalize your Web experience! Add custom buttons to get the information you care about most.