Assume that you're trying to create the following folder:
You could easily create it if the folder C:\Folder1\Folder2\Folder3 existed by simply calling the MkDir method:
However, VB flags a run-time error if the C:\folder1\folder2\folder3 does not exists. The following function makes creating subfolders more easier by checking all the parent folders and creating any of them if they did not exist using recursion.
To use this function, simply pass the FULL PATH of the folder you wish to create. Make sure that destDir always end with "\" (without quotes). The function returns TRUE if operation was successful. Otherwise, it returns FALSE.
Public Function CreateFolder(destDir As String) As Boolean
Dim i As Long
Dim prevDir As String
On Error Resume Next
For i = Len(destDir) To 1 Step -1
If Mid(destDir, i, 1) = "\" Then
prevDir = Left(destDir, i - 1)
If prevDir = "" Then CreateFolder = False: Exit Function
If Not Len(Dir(prevDir & "\", vbDirectory)) > 0 Then
If Not CreateFolder(prevDir) Then CreateFolder = False: Exit Function
On Error GoTo errDirMake
CreateFolder = True
CreateFolder = False
If CreateFolder("C:\Folder1\Folder2\Folder3\") Then
MsgBox "Folder Creation successful!"
MsgBox "Folder Creation failed!"