
Syntax
VBA
path: The path of the directory you want to create. This can be a relative or an absolute path.
MkDir path
How to Use
Basic Usage
VBA
This command will create a new folder named “NewFolder” in the C drive.
MkDir "C:NewFolder"
Creating Nested Directories
If you need to create a subdirectory within a directory that does not yet exist, you must create each directory in the hierarchy separately. For example, to create “C:NewFolderSubFolder”, you must first create “NewFolder” and then create “SubFolder” within it.VBA
MkDir "C:NewFolder"
MkDir "C:NewFolderSubFolder"
Error Handling
It’s important to handle errors with MkDir, as attempting to create a directory that already exists will result in a runtime error. You can use error handling to manage this:VBA
This error handling will catch the error and display a message box if the directory cannot be created.
On Error Resume Next
MkDir "C:NewFolder"
If Err.Number <> 0 Then
MsgBox "Directory could not be created: " & Err.Description
End If
On Error GoTo 0
Using Variables for Path
You can also use a variable to hold the path string, which can be useful for dynamic directory creation.VBA
Dim myPath As String
myPath = "C:NewFolder"
MkDir myPath
Important Considerations
- Permission: The user running the VBA script must have sufficient permissions to create a directory in the specified location.
- Existing Directory: As mentioned, attempting to create a directory that already exists will cause an error.
- Network Paths: MkDir can also be used to create directories on network paths, as long as the path is accessible and permissions are adequate.