How to use MkDir statement in VBA?

The MkDir statement in VBA (Visual Basic for Applications) is used to create new directories. It’s a straightforward command, but there are some important considerations to keep in mind when using it.

Syntax

VBA
MkDir path

path: The path of the directory you want to create. This can be a relative or an absolute path.

How to Use

Basic Usage

VBA
MkDir "C:\NewFolder"

This command will create a new folder named “NewFolder” in the C drive.

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:\NewFolder\SubFolder”, you must first create “NewFolder” and then create “SubFolder” within it.

VBA
MkDir "C:\NewFolder"
MkDir "C:\NewFolder\SubFolder"

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
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

This error handling will catch the error and display a message box if the directory cannot be created.

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.

MkDir is a simple but effective way to create directories directly from your VBA code, aiding in tasks like file organization and data management.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project

Leave a Reply

Your email address will not be published. Required fields are marked *