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
It's a very useful function in VBA. Thanks.
ReplyDeleteHere is an other solution based on the same coding logic!
ReplyDeletehttp://vbaexcel.eu/vba-macro-code/determine-if-file-or-directory-exists
It's telling me the function File_Exists does not exist.
ReplyDeleteIt's telling me the function File_Exists does not exist
ReplyDelete!cause U HAVE to paste ths n workbook or wherever u using da code:!
DeletePrivate 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
just change private to public
Deletei haven't used access 2007 but in 2003 i use FileExists instead of File_Exists
ReplyDeletehttp://allenbrowne.com/func-11.html
ReplyDelete