Directory Exists

Created by Rob Bovey:
Uses path as argument and it returns True if the
path is empty or doesn’t exist and False if the path contains files.

Function bIsEmpty(ByVal szPath As String) As Boolean
    Dim bReturn As Boolean
    Dim szTemp As String
    bReturn = True
    If Right$(szPath, 1) <> “” Then szPath = szPath & “”
    szTemp = Dir$(szPath & “*.*”)
    If szTemp <> “” Then bReturn = False
    bIsEmpty = bReturn
End Function

Editor’s note: I guess I never realized that Dir was string function. Jake pointed out in String Function Efficiency that I should use the dollar sign, and by gosh I’ve really tried. Now I’ll have to beat it into my head to use it with Dir too.

Posted in Uncategorized

One thought on “Directory Exists

  1. For FileExists, I use the following, which I swiped from a post by Karl Peterson, VB MVP (FileSpec is the full file and path name):

    Function FileExists(ByVal FileSpec As String) As Boolean
    ‘ Karl Peterson MS VB MVP
    Dim Attr As Long
    ‘ Guard against bad FileSpec by ignoring errors
    ‘ retrieving its attributes.
    On Error Resume Next
    Attr = GetAttr(FileSpec)
    If Err.Number = 0 Then
    ‘ No error, so something was found.
    ‘ If Directory attribute set, then not a file.
    FileExists = Not ((Attr And vbDirectory) = vbDirectory)
    End If
    End Function

    I tweaked it a little (all by myself!) for DirExists:

    Function DirExists(ByVal FileSpec As String) As Boolean
    ‘ Karl Peterson MS VB MVP
    Dim Attr As Long
    ‘ Guard against bad FileSpec by ignoring errors
    ‘ retrieving its attributes.
    On Error Resume Next
    Attr = GetAttr(FileSpec)
    If Err.Number = 0 Then
    ‘ No error, so something was found.
    ‘ If Directory attribute set, then not a file.
    DirExists = (Attr And vbDirectory) = vbDirectory
    End If
    End Function

    I haven’t come across the need for DirEmpty. It seems I’d want to know the difference between a directory being empty and not existing at all, so I’d probably use DirExists, then do Dir$ on *.* within the path.

    – Jon


Posting code? Use <pre> tags for VBA and <code> tags for inline.

Leave a Reply

Your email address will not be published.