Normally to create a new folder just right click empty area at Desktop or inside any folders then click at New and click folder. By default the folder name is New Folder and we have to rename accordingly but if the folder name already exist then we have give another name.
How to create Folder and Sub folders with VBA code?
A few items need to consider in order to create folder:
- Path or Directory
- Folder Existence
- Create Folder
Path or Directory - Common Directory:
- C (C:)
- Documents (C:\Users\Username\Documents)
- Desktop (C:\Users\Username\Desktop)
The problem is Username not fixed, it could be Admin, Guest or any name given. In order to get actual Username we use below code:
'OR
VBA.Environ ("Username") 'This will give us Username
Folder existence
To check folder exists or not we use below code:
If Dir(YourPath, vbDirectory) = "" Then
MkDir YourPath
End If
Create Folder
To create folder we use
Below completed code to create folder and sub folder:
Sub CreatingFolderAndSubFolder()
'Declare Variables
Dim StrOuterPath As String, StrInnerPath As String
'To Create New Folder name "Main Folder"
StrOuterPath = VBA.Environ("UserProfile") & "\" & "Desktop" & "\" & "Main Folder"
'To Create New Folder Inside Main Folder name "Sub Folder"
StrInnerPath = VBA.Environ("UserProfile") & "\" & "Desktop" & "\" & "Main Folder" & "\" & "Sub Folder"
'To Check Main Folder existence
If Dir(StrOuterPath, vbDirectory) = "" Then
'To Create Main Folder
MkDir StrOuterPath
'To Create Sub Folder
MkDir StrInnerPath
MsgBox "Main and Sub Folder Successfully created"
Else
'To Check Sub Folder existence
If Dir(StrInnerPath, vbDirectory) = "" Then
'To Create Sub Folder
MkDir StrInnerPath
MsgBox "Sub Folder Successfully created"
Else
MsgBox "Main Folder and Sub Folder already exist"
End If
End If
'Reset Variables
StrOuterPath = "": StrInnerPath = ""
End Sub
Thank You