VB and VBA Users Source Code: Check if a file exists (using its attributes)
[
Home
|
Contents
|
Search
|
Reply
| Previous |
Next
]
VB/VBA Source Code
Check if a file exists (using its attributes)
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Monday, July 03, 2000
Hits:
1035
Category:
Files/Directories/IO
Article:
Using the Dir function to check if a file exists can be problematic, especially if the file name could contain an empty string. The safest method of checking if a file exists is to check it's attributes. Option Explicit 'Purpose : Checks if a file exists 'Inputs : sFilePathName The path and file name e.g. "C:\Autoexec.bat" 'Outputs : Returns True if the file exists 'Author : Andrew Baker 'Date : 25/11/2000 03:33 'Notes : Supports the use of wildcard characters. ' eg. Debug.Print FileExists("C:\*.bat") ' Would return true if a file ending in .bat existed on C:\ 'Revisions : Function FileExists(sFilePathName As String) As Boolean Dim sWildCardFile As String On Error GoTo ErrFailed FileExists = False If Len(sFilePathName) Then If (GetAttr(sFilePathName) And vbDirectory) < 1 Then 'File Exists FileExists = True End If End If Exit Function ErrFailed: 'Failed, check wildcards If InStr(1, sFilePathName, "*") > 0 Or InStr(1, sFilePathName, "$") > 0 Then 'File contains Wild Cards sWildCardFile = Dir$(sFilePathName) If CBool(Len(sWildCardFile)) Then If (GetAttr(PathFileToPath(sFilePathName) & sWildCardFile) And vbDirectory) < 1 Then 'File Exists FileExists = True End If End If End If On Error GoTo 0 End Function 'Purpose : Converts a File Name and Path to a Path 'Inputs : sFilePathName The path and file name e.g. "C:\Autoexec.bat" 'Outputs : Returns the path give a file and path name e.g. "C:\Autoexec.bat" would return "C:\" 'Author : Andrew Baker 'Date : 25/11/2000 03:33 'Notes : 'Revisions : Function PathFileToPath(sFilePathName As String) As String Dim lPos As Long lPos = InStrRev(sFilePathName, "\") If lPos Then PathFileToPath = Left$(sFilePathName, lPos) Else PathFileToPath = sFilePathName End If End Function
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder