Function Check If Folder Exists

Function Test If Folder Exists




VBA Code:
Function FolderExists(sFile As Variant) As Boolean
On Error Resume Next
If Len(sFile) > 0 Then
        FolderExists = (Len(Dir$(sFile, vbDirectory)) > 0&)
End If
End Function
How to Use It:

Put the VBA code above on form or in the Module and call it on the click button on your Access file where you want to check if this form exists before call process the next step.

If you call a certain folder or file path that does not exist then you will get an error. So this function is to prevent the error for calling non-existing folder.

For example below, when a button Command2 is clicked, program will looking for folder “Math1” under the C:\Dropbox. If there is no such C:\Dropbox\Math1 folder/path then it will create the Math1 folder under C:\Dropbox folder. If the folder already exists then the message “This folder already exists.” will pop-up.

Example:

Put this function under the same form of your click button:

Private Sub Command2_Click()
Dim strFilePath As String
strFilePath = “C:\Dropbox \Math1”
If FolderExists (strFilePath) = False Then
          Call MakeDir(strFilePath)  ‘ Call MakeDir function to create a folder if it does not exist  
Else               
          MsgBox "This folder already exists.", vbInformation, "Folder Exists"
End If
End Sub

Function FolderExists(sFile As Variant) As Boolean
On Error Resume Next
If Len(sFile) > 0 Then
       FolderExists = (Len(Dir$(sFile, vbDirectory)) > 0&)
End If
End Function

 

Note: you can also place the FolderExists function under the Module and call this function from any form in your access file.