totn Excel Functions

MS Excel: How to use the MKDIR Statement (VBA)

This Excel tutorial explains how to use the Excel MKDIR statement with syntax and examples.

Description

The Microsoft Excel MKDIR statement allows you to create a new folder or directory.

The MKDIR function is a built-in function in Excel that is categorized as a File/Directory Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.

Syntax

The syntax for the MKDIR statement in Microsoft Excel is:

MkDir path

Parameters or Arguments

path
The folder or directory to create.

Returns

The MKDIR statement does not return a value, but rather creates a new folder or directory.
If path is a complex directory structure, the high-level directories must already exist or the MKDIR statement will raise an error.

For example, if you executed the following code:

MkDir "c:\Test\Excel"

The c:\Test directory must already exist. The MKDIR statement will only attempt to create the Excel directory under the c:\Test directory. It will not create the c:\Test directory itself.

Applies To

  • Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Type of Function

  • VBA function (VBA)

Example (as VBA Statement)

The MKDIR statement can only be used in VBA code in Microsoft Excel.

Let's look at some Excel MKDIR statement function examples and explore how to use the MKDIR statement in Excel VBA code:

MkDir "c:\TOTN\Examples"

In this example, the MKDIR statement would create a new directory called Examples under the c:\TOTN directory.

For example:

MkDir "c:\TOTN\Examples\Files"

In this example, the directory called Files would be created under the c:\TOTN\Examples directory.

Frequently Asked Questions

Question: I'm not sure if a particular directory exists already. If it doesn't exist, I'd like to create it using VBA code. How can I do this?

Answer: You can test to see if a directory exists using the VBA code below:

If Len(Dir("c:\TOTN\Excel\Examples", vbDirectory)) = 0 Then
   MkDir "c:\TOTN\Excel\Examples"
End If

In this example, the code would first check to see if the c:\TOTN\Excel\Examples directory exists. If it doesn't exist, the MKDIR statement would create a new directory called Examples under the c:\TOTN\Excel directory.