Microsoft Access: VBA Programming Code

Provided by Allen Browne, June 2006

FileExists() and FolderExists() functions

Use these functions to determine whether a file or directory is accessible.
They are effectively wrappers for Dir() and GetAttr() respectively.
Searching an invalid network name can be slow.


This function returns True if there is a file with the name you pass in, even if it is a hidden or system file.
Assumes the current directory if you do not include a path.

Returns False if the file name is a folder, unless you pass True for the second argument.
Returns False for any error, e.g. invalid file name, permission denied, server not found.

Does not search subdirectories. To enumerate files in subfolders, see List files recursively.


This function returns True if the string you supply is a directory.
Return False for any error: server down, invalid file name, permission denied, and so on.


Use the TrailingSlash() function to add a slash to the end of a path unless it is already there.


  1. Look for a file named MyFile.mdb in the Data folder:
  2. Look for a folder named System in the Windows folder on C: drive:
  3. Look for a file named MyFile.txt on a network server:
  4. Check for a file or folder name Wotsit on the server:
        FileExists("\\MyServer\Wotsit", True)
  5. Check the folder of the current database for a file named GetThis.xls:
        FileExists(TrailingSlash(CurrentProject.Path) & "GetThis.xls")

The code

Function FileExists(ByVal strFile As String, Optional bFindFolders As Boolean) As Boolean
    'Purpose:   Return True if the file exists, even if it is hidden.
    'Arguments: strFile: File name to look for. Current directory searched if no path included.
    '           bFindFolders. If strFile is a folder, FileExists() returns False unless this argument is True.
    'Note:      Does not look inside subdirectories for the file.
    'Author:    Allen Browne. June, 2006.
    Dim lngAttributes As Long

    'Include read-only files, hidden files, system files.
    lngAttributes = (vbReadOnly Or vbHidden Or vbSystem)

    If bFindFolders Then
        lngAttributes = (lngAttributes Or vbDirectory) 'Include folders as well.
        'Strip any trailing slash, so Dir does not look inside the folder.
        Do While Right$(strFile, 1) = "\"
            strFile = Left$(strFile, Len(strFile) - 1)
    End If

    'If Dir() returns something, the file exists.
    On Error Resume Next
    FileExists = (Len(Dir(strFile, lngAttributes)) > 0)
End Function

Function FolderExists(strPath As String) As Boolean
    On Error Resume Next
    FolderExists = ((GetAttr(strPath) And vbDirectory) = vbDirectory)
End Function

Function TrailingSlash(varIn As Variant) As String
    If Len(varIn) > 0 Then
        If Right(varIn, 1) = "\" Then
            TrailingSlash = varIn
            TrailingSlash = varIn & "\"
        End If
    End If
End Function

HomeIndex of tipsTop