VBA check if file exists VBA check if file exists vba vba

VBA check if file exists


something like this

best to use a workbook variable to provide further control (if needed) of the opened workbook

updated to test that file name was an actual workbook - which also makes the initial check redundant, other than to message the user than the Textbox is blank

Dim strFile As StringDim WB As WorkbookstrFile = Trim(TextBox1.Value)Dim DirFile As StringIf Len(strFile) = 0 Then Exit SubDirFile = "C:\Documents and Settings\Administrator\Desktop\" & strFileIf Len(Dir(DirFile)) = 0 Then  MsgBox "File does not exist"Else On Error Resume Next Set WB = Workbooks.Open(DirFile) On Error GoTo 0 If WB Is Nothing Then MsgBox DirFile & " is invalid", vbCriticalEnd If


I use this function to check for file existence:

Function IsFile(ByVal fName As String) As Boolean'Returns TRUE if the provided name points to an existing file.'Returns FALSE if not existing, or if it's a folder    On Error Resume Next    IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory)End Function


For checking existence one can also use (works for both, files and folders):

Not Dir(DirFile, vbDirectory) = vbNullString

The result is True if a file or a directory exists.

Example:

If Not Dir("C:\Temp\test.xlsx", vbDirectory) = vbNullString Then    MsgBox "exists"Else    MsgBox "does not exist"End If