Provided by Allen Browne, June 2006
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.
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. http://allenbrowne.com 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. Else 'Strip any trailing slash, so Dir does not look inside the folder. Do While Right$(strFile, 1) = "\" strFile = Left$(strFile, Len(strFile) - 1) Loop 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 Else TrailingSlash = varIn & "\" End If End If End Function
Home | Index of tips | Top |