Objective:
To create a folder in VBA .
Approach
Here we are first checking if the folder already exists, if it does not exist then we are using mkdir command to create the folder.
Steps
- Declare and define a variable which has the path where folder will be created
- Check if the folder already exists using Dir method.
- If folder does not exist, then create the folder using mkdir command
- If folder already exists, then display the message that folder already exists.
Code
Sub CreateFolder() Dim MyFolderName As String 'Path where the folder will be created MyFolderName = "C:\Users\YourUserName\Desktop\macro\Final\MyCreatedFolder" 'Check if the folder already exists, Here Dir function with vbDirectory returns the name of the folder [which is MyFolderName here] If Dir(MyFolderName, vbDirectory) = "" Then 'Create a folder using mkdir command MkDir MyFolderName ' Display a message box if folder already exists Else MsgBox "Folder Already Exists" End If End Sub
Note
(1) You can customize below code if you want to save your files at a particular folder.
(2) You can make your folder name dynamic, by taking the input from user by input box in VBA.
Reference
https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/mkdir-statement
https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/dir-function
Post you may like
How to use Immediate Window , Watch Window and Local Window for VBA Debugging ?
1 comment on “Create a folder by mkdir statement in VBA”
Comments are closed.