Access VBA lookup folder and create if does not ex

2019-06-04 05:57发布

问题:

I'm building a small program using Access 2010 and am using the below to check for a folder and if it doesn't exist, then create it, which works:

'need code to create folder
    If Dir("C:\Michael\Test", vbDirectory) = "" Then
        MkDir ("C:\Michael\Test")
    Else
        'do nothing for directory already exists
    End If

However, I need to modify this. The path can change depending on what the user has selected. At the moment the path is built up and saved in a table ("tmpDestFolders") in field ("FlatFile").

In effect, I need to lookup whatever this value is, but the below does not work - how can I changed it so it will check what ever the field value is? I just keep receiving error 76 invalid path:

'need code to create folder
    If Dir(DLookup("FlatFile", "tmpDestFolders"), vbDirectory) = "" Then
        MkDir (DLookup("FlatFile", "tmpDestFolders"))
    Else
        'do nothing for directory already exists
    End If

回答1:

Use an API call:

Private Declare Function MakeSureDirectoryPathExists Lib "imagehlp.dll" (ByVal lpPath As String) As Long

and then simply:    

MakeSureDirectoryPathExists DLookup("FlatFile", "tmpDestFolders")


回答2:

@Gustav's Example is great as it's a one liner. My function while it contains more lines of code adds a flag option that if you choose to do so will create the directory for you if you set it to true. It's a nice one to add to the library. It's based off of the Access Master's (Allen Brown) function Folder Exists

Function FolderExistsCreate(DirectoryPath As String, CreateIfNot As Boolean) As Boolean
    Dim Exists As Boolean
    On Error GoTo DoesNotExist
    Exists = ((GetAttr(DirectoryPath) And vbDirectory) = vbDirectory)

    If Exists Then
        FolderExistsCreate = True
    Else
        ' Doesn't Exist Determine If user Wants to create
        If CreateIfNot Then
            MkDir DirectoryPath
            FolderExistsCreate = True
        Else
            FolderExistsCreate = False
        End If
    End If
    Exit Function
DoesNotExist:
    FolderExistsCreate = False
End Function

Notes: This can easily be called for example if you just want to create a directory if it does not exist like:

Call FolderExistsCreate(strPath, True)

Or if you want to test if a folder exists then create if not like:

' Check for User Specified 'Local' Dir Inbound Dir
If FolderExistsCreate(strPath, True) Then
    ValidateInboundLocal = True
Else
    ValidateInboundLocal = False
End If

Or if you just want to check for a directory without creating it like:

' Check for User Specified 'Local' Dir Inbound Dir
If FolderExistsCreate(strPath, False) Then
    ValidateInboundLocal = True
Else
    ValidateInboundLocal = False
End If