How to Check file exists (in Six ways)
Posted on January 4, 2009
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | 'File/Folder Handling - How to Check file exists (in Six ways) 'Using Dir: Private Function FileExistsWithDir(ByVal sFileName As String) As Boolean On Error Resume Next FileExistsWithDir = (Dir$(sFileName) <> "") End Function 'Using File Open: Private Function FileExistsWithOpen(ByVal filename As String) As Boolean Dim fnum As String fnum = FreeFile On Error GoTo FileDoesntExist Open filename For Input As fnum Close fnum FileExistsWithOpen = True Exit Function FileDoesntExist: FileExistsWithOpen = False End Function 'Using File Length: Private Function FileExistsWithFileLen(ByVal filename As String) As Boolean Dim length As Long On Error GoTo FileDoesntExist length = FileLen(filename) FileExistsWithFileLen = True Exit Function FileDoesntExist: FileExistsWithFileLen = False End Function 'Using File Attribute: Private Function FileExistsWithAttrib(ByVal sFileName As String) As Boolean Dim lRetVal As Long On Error GoTo FileDoesntExist: lRetVal = GetAttr(sFileName) FileExistsWithAttrib = True Exit Function FileDoesntExist: FileExistsWithAttrib = False End Function 'Using API: Private Declare Function PathFileExists Lib "shlwapi.dll" Alias "PathFileExistsA" _ (ByVal pszPath As String) As Long Private Function FileExistsUsingAPI(ByVal sFileName As String) As Boolean If CBool(PathFileExists("C:\Temp\Test.txt")) Then FileExistsUsingAPI = True Else FileExistsUsingAPI = False End If End Function 'Using FSO: Public Function FileExistsUsingFSO(ByVal sFileName As String) As Boolean 'Set a reference to "Microsoft Scripting Runtime" Dim FSO As Scripting.FileSystemObject Set FSO = New Scripting.FileSystemObject FileExistsUsingFSO = FSO.FileExists(sFileName) Set FSO = Nothing End Function |