Создание, копирование, перемещение и удаление папок в VBA Excel методами объекта FileSystemObject. Удаление папок с помощью оператора RmDir.
Создание папки (метод CreateFolder)
CreateFolder – это метод объекта FileSystemObject, предназначенный для создания новой папки.
Синтаксис
object.CreateFolder (foldername) |
Параметр foldername
можно в скобки не заключать.
Параметры
Параметр | Описание |
---|---|
object | Переменная, возвращающая объект FileSystemObject. |
foldername | Строковое выражение, указывающее папку, которую необходимо создать. |
Если папка, указанная параметром foldername
уже существует, произойдет ошибка.
Копирование папки (метод CopyFolder)
CopyFolder – это метод объекта FileSystemObject, предназначенный для копирования папки из одного расположения в другое.
Синтаксис
object.CopyFolder source, destination, [overwrite] |
Параметры
Параметр | Описание |
---|---|
object | Переменная, возвращающая объект FileSystemObject. |
source | Строковое выражение, указывающее папку, которую требуется скопировать в другое расположение. Для копирования нескольких папок используются подстановочные знаки. |
destination | Строковое выражение, задающее конечное расположение, куда требуется скопировать папку (папки) со всеми вложениями из элемента source. Подстановочные знаки не допускаются. |
overwrite | Логическое значение, которое указывает, требуется ли перезаписывать существующие папки и файлы в конечном расположении. True – папки и файлы будут перезаписаны, False – перезапись не выполняется. Необязательный параметр. По умолчанию – True. |
Перемещение папки (метод MoveFolder)
MoveFolder – это метод объекта FileSystemObject, предназначенный для перемещения папки из одного расположения в другое.
Синтаксис
object.MoveFolder (source, destination) |
Параметры
Параметр | Описание |
---|---|
object | Переменная, возвращающая объект FileSystemObject. |
source | Строковое выражение, указывающее папку, которую требуется переместить в другое расположение. Для перемещения нескольких папок используются подстановочные знаки. |
destination | Строковое выражение, задающее конечное расположение, куда требуется переместить папку (папки) со всеми вложениями из элемента source. Подстановочные знаки не допускаются. |
Удаление папки (метод DeleteFolder)
DeleteFolder – это метод объекта FileSystemObject, предназначенный для удаления папки с диска со всем ее содержимым.
Синтаксис
object.DeleteFolder folderspec, [force] |
Параметры
Параметр | Описание |
---|---|
object | Переменная, возвращающая объект FileSystemObject. |
folderspec | Строковое выражение, указывающее папку, которую следует удалить. Для удаления нескольких папок используются подстановочные знаки. |
force | Значение типа Boolean: True – удаляются все папки, False (по умолчанию) – не удаляются папки с атрибутом «только для чтения» (необязательный параметр). |
Метод DeleteFolder
удаляет папки независимо от того, есть ли в них содержимое или нет.
Удаление папки (оператор RmDir)
RmDir – это оператор, предназначенный для удаления пустых папок и каталогов.
Синтаксис
- path – строковое выражение, определяющее каталог или папку, которую необходимо удалить.
Если удаляемый каталог или папка содержит файлы, произойдет ошибка.
Примеры
Пример 1
Создание папок в VBA Excel с помощью метода CreateFolder:
Sub Primer1() Dim fso As Object, i As Integer ‘Создаем новый экземпляр FileSystemObject Set fso = CreateObject(«Scripting.FileSystemObject») ‘Создаем несколько новых папок With fso .CreateFolder («C:Папка главная») For i = 1 To 5 .CreateFolder «C:Папка главнаяПапка « & i Next End With End Sub |
В результате работы этого кода на диске C
будет создана Папка главная
и в ней еще 5 папок, которые будем использовать для копирования, перемещения и удаления.
Пример 2
Копирование папок в VBA Excel с помощью метода CopyFolder:
Sub Primer2() Dim fso As Object Set fso = CreateObject(«Scripting.FileSystemObject») ‘Копируем папки With fso .CopyFolder «C:Папка главнаяПапка 2», «C:Папка главнаяПапка 1» .CopyFolder «C:Папка главнаяПапка 3«, «C:Папка главнаяПапка 1Папка 2« End With End Sub |
Код этого примера копирует папки следующим образом: Папка 2
в Папка 1
, а Папка 3
в расположение Папка 1Папка 2
.
Пример 3
Перемещение папок в VBA Excel с помощью метода MoveFolder:
Sub Primer3() Dim fso As Object Set fso = CreateObject(«Scripting.FileSystemObject») ‘Перемещаем папки With fso .MoveFolder «C:Папка главнаяПапка 3», «C:Папка главнаяПапка 2» .MoveFolder «C:Папка главнаяПапка 4«, «C:Папка главнаяПапка 2« .MoveFolder «C:Папка главнаяПапка 5», «C:Папка главнаяПапка 2Папка 4« End With End Sub |
Пример 4
Удаление папок в VBA Excel с помощью метода DeleteFolder:
Sub Primer4() Dim fso As Object Set fso = CreateObject(«Scripting.FileSystemObject») ‘Удаляем папки с содержимым With fso .DeleteFolder «C:Папка главнаяПапка 1» .DeleteFolder «C:Папка главнаяПапка 2» End With End Sub |
Пример 5
Удаление пустой папки в VBA Excel с помощью оператора RmDir:
Sub Primer5() ‘Удаляем пустую папку RmDir «C:Папка главная» End Sub |
VBA MkDir function in Excel is categorized as File and Directory function. This built-in VBA MkDir function creates a new folder or directory in Excel VBA. If the folder or the directory already exists, returns an error.
This function use in either procedure or function in a VBA editor window in Excel. We can use this VBA MkDir Function in any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the MkDir function, where we can use this MkDir Function and real-time examples in Excel VBA.
Table of Contents:
- Overview
- Syntax of VBA MkDir Function
- Parameters or Arguments
- Where we can apply or use VBA MkDir Function?
- Example 1: Create a New Folder
- Example 2: Check and Create a New Directory
- Example 3: Create Directory in the Current Drive
- Example 4: Create a New Folder(Returns an Error)
- Instructions to Run VBA Macro Code
- Other Useful Resources
The syntax of the MkDir Function in VBA is
MkDir(Path)
The MkDir Function doesn’t return any value. It creates a new folder or directory.
Parameters or Arguments:
The MkDir function/statement has one argument in Excel VBA.
where
Path: It is a mandatory string parameter. The path argument represents the folder or directory to create.
Where we can apply or use VBA MkDir Function?
We can use this MkDir Function in VBA MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.
Example 1: Create a New Folder
Here is a simple example of the VBA MkDir function. This below example create a new foler and displays message.
'Create a New Folder Sub VBA_MkDir_Function_Ex1() 'Variable declaration Dim sPath As String sPath = "C:SomeswariVBAF1VBA FunctionsVBA Text FunctionsTest" MkDir sPath MsgBox "Folder has created : " & vbCrLf & sPath, vbInformation, "VBA MkDir Function" End Sub
Output: Here is the screen shot of the first example output.
Example 2: Check and Create a New Directory
Here is a simple example of the VBA MkDir function. This below example checks for the direcetory exists or not. If it doesn’t exists, creates a new directory.
'Check and Create a New Directory Sub VBA_MkDir_Function_Ex2() 'Variable declaration Dim sPath As String sPath = "C:Test" If Len(Dir(sPath, vbDirectory)) = 0 Then MkDir sPath MsgBox "Directory Created Successfully : " & vbCrLf & sPath, vbInformation, "VBA MkDir Function" End If End Sub
Output: Here is the screen shot of the second example output.
Example 3: Create Directory in the Current Drive
Here is a simple example of the VBA MkDir function. This below example checks for the drive exists or not. If it doesn’t exists, creates a folder in the current drive.
'Create Directory in the Current Drive Sub VBA_MkDir_Function_Ex3() 'Variable declaration Dim sPath As String sPath = "Test_Drive" If Len(Dir(sPath, vbDirectory)) = 0 Then MkDir sPath MsgBox "Created Directory in the current drive : " & vbCrLf & sPath, vbInformation, "VBA MkDir Function" End If End Sub
Output: Here is the screen shot of the third example output.
Example 4: Create a New Folder(Returns an Error)
Here is a simple example of the VBA MkDir function. This below example returns an error. Because the folder is already exists.
'Create a New Folder Sub VBA_MkDir_Function_Ex4() 'Variable declaration Dim sPath As String sPath = "C:SomeswariVBAF1VBA FunctionsVBA Text FunctionsTest" 'Note: Folder is already available. MkDir sPath MsgBox "Folder doesn't create : " & vbCrLf & sPath, vbInformation, "VBA MkDir Function" End Sub
Output: Here is the screen shot of the fourth example output.
Instructions to Run VBA Macro Code or Procedure:
You can refer the following link for the step by step instructions.
Instructions to run VBA Macro Code
Other Useful Resources:
Click on the following links of the useful resources. These helps to learn and gain more knowledge.
VBA Tutorial VBA Functions List VBA Arrays in Excel Blog
VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers
I have a pull down menu of companies that is populated by a list on another sheet. Three columns, Company, Job #, and Part Number.
When a job is created I need a folder for said company and a sub-folder for said Part Number.
If you go down the path it would look like:
C:ImagesCompany NamePart Number
If either company name or Part number exists don’t create, or overwrite the old one. Just go to next step. So if both folders exist nothing happens, if one or both don’t exist create as required.
Another question is there a way to make it so it works on Macs and PCs the same?
asked May 29, 2012 at 17:23
16
Another simple version working on PC:
Sub CreateDir(strPath As String)
Dim elm As Variant
Dim strCheckPath As String
strCheckPath = ""
For Each elm In Split(strPath, "")
strCheckPath = strCheckPath & elm & ""
If Len(Dir(strCheckPath, vbDirectory)) = 0 Then MkDir strCheckPath
Next
End Sub
answered Nov 12, 2015 at 12:23
MartinMartin
6815 silver badges4 bronze badges
5
One sub and two functions. The sub builds your path and use the functions to check if the path exists and create if not. If the full path exists already, it will just pass on by.
This will work on PC, but you will have to check what needs to be modified to work on Mac as well.
'requires reference to Microsoft Scripting Runtime
Sub MakeFolder()
Dim strComp As String, strPart As String, strPath As String
strComp = Range("A1") ' assumes company name in A1
strPart = CleanName(Range("C1")) ' assumes part in C1
strPath = "C:Images"
If Not FolderExists(strPath & strComp) Then
'company doesn't exist, so create full path
FolderCreate strPath & strComp & "" & strPart
Else
'company does exist, but does part folder
If Not FolderExists(strPath & strComp & "" & strPart) Then
FolderCreate strPath & strComp & "" & strPart
End If
End If
End Sub
Function FolderCreate(ByVal path As String) As Boolean
FolderCreate = True
Dim fso As New FileSystemObject
If Functions.FolderExists(path) Then
Exit Function
Else
On Error GoTo DeadInTheWater
fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
Exit Function
End If
DeadInTheWater:
MsgBox "A folder could not be created for the following path: " & path & ". Check the path name and try again."
FolderCreate = False
Exit Function
End Function
Function FolderExists(ByVal path As String) As Boolean
FolderExists = False
Dim fso As New FileSystemObject
If fso.FolderExists(path) Then FolderExists = True
End Function
Function CleanName(strName as String) as String
'will clean part # name so it can be made into valid folder name
'may need to add more lines to get rid of other characters
CleanName = Replace(strName, "/","")
CleanName = Replace(CleanName, "*","")
etc...
End Function
answered May 29, 2012 at 18:43
Scott HoltzmanScott Holtzman
27k5 gold badges36 silver badges72 bronze badges
16
I found a much better way of doing the same, less code, much more efficient. Note that the «»»» is to quote the path in case it contains blanks in a folder name. Command line mkdir creates any intermediary folder if necessary to make the whole path exist.
If Dir(YourPath, vbDirectory) = "" Then
Shell ("cmd /c mkdir """ & YourPath & """")
End If
answered Nov 14, 2014 at 16:42
4
Private Sub CommandButton1_Click()
Dim fso As Object
Dim fldrname As String
Dim fldrpath As String
Set fso = CreateObject("scripting.filesystemobject")
fldrname = Format(Now(), "dd-mm-yyyy")
fldrpath = "C:Temp" & fldrname
If Not fso.FolderExists(fldrpath) Then
fso.createfolder (fldrpath)
End If
End Sub
ZygD
21k39 gold badges77 silver badges98 bronze badges
answered Mar 13, 2014 at 18:50
1
There are some good answers on here, so I will just add some process improvements. A better way of determining if the folder exists (does not use FileSystemObjects, which not all computers are allowed to use):
Function FolderExists(FolderPath As String) As Boolean
FolderExists = True
On Error Resume Next
ChDir FolderPath
If Err <> 0 Then FolderExists = False
On Error GoTo 0
End Function
Likewise,
Function FileExists(FileName As String) As Boolean
If Dir(FileName) <> "" Then FileExists = True Else FileExists = False
EndFunction
answered Aug 17, 2016 at 15:26
SandPiperSandPiper
2,7765 gold badges32 silver badges49 bronze badges
Function MkDir(ByVal strDir As String)
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(strDir) Then
' create parent folder if not exist (recursive)
MkDir (fso.GetParentFolderName(strDir))
' doesn't exist, so create the folder
fso.CreateFolder strDir
End If
End Function
ZygD
21k39 gold badges77 silver badges98 bronze badges
answered Oct 23, 2019 at 7:27
ZoynelsZoynels
211 silver badge2 bronze badges
3
This works like a charm in AutoCad VBA and I grabbed it from an excel forum. I don’t know why you all make it so complicated?
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:
(Quotes below are omitted to avoid confusion of programming code)
If Len(Dir("c:TOTNExcelExamples", vbDirectory)) = 0 Then
MkDir "c:TOTNExcelExamples"
End If
http://www.techonthenet.com/excel/formulas/mkdir.php
answered Jan 15, 2015 at 4:13
BrettBrett
271 bronze badge
1
For those looking for a cross-platform way that works on both Windows and Mac, the following works:
Sub CreateDir(strPath As String)
Dim elm As Variant
Dim strCheckPath As String
strCheckPath = ""
For Each elm In Split(strPath, Application.PathSeparator)
strCheckPath = strCheckPath & elm & Application.PathSeparator
If (Len(strCheckPath) > 1 And Not FolderExists(strCheckPath)) Then
MkDir strCheckPath
End If
Next
End Sub
Function FolderExists(FolderPath As String) As Boolean
FolderExists = True
On Error Resume Next
ChDir FolderPath
If Err <> 0 Then FolderExists = False
On Error GoTo 0
End Function
answered May 29, 2020 at 8:22
Never tried with non Windows systems, but here’s the one I have in my library, pretty easy to use. No special library reference required.
Function CreateFolder(ByVal sPath As String) As Boolean
'by Patrick Honorez - www.idevlop.com
'create full sPath at once, if required
'returns False if folder does not exist and could NOT be created, True otherwise
'sample usage: If CreateFolder("C:tototesttest") Then debug.print "OK"
'updated 20130422 to handle UNC paths correctly ("\MyServerMyShareMyFolder")
Dim fs As Object
Dim FolderArray
Dim Folder As String, i As Integer, sShare As String
If Right(sPath, 1) = "" Then sPath = Left(sPath, Len(sPath) - 1)
Set fs = CreateObject("Scripting.FileSystemObject")
'UNC path ? change 3 "" into 3 "@"
If sPath Like "\**" Then
sPath = Replace(sPath, "", "@", 1, 3)
End If
'now split
FolderArray = Split(sPath, "")
'then set back the @ into in item 0 of array
FolderArray(0) = Replace(FolderArray(0), "@", "", 1, 3)
On Error GoTo hell
'start from root to end, creating what needs to be
For i = 0 To UBound(FolderArray) Step 1
Folder = Folder & FolderArray(i) & ""
If Not fs.FolderExists(Folder) Then
fs.CreateFolder (Folder)
End If
Next
CreateFolder = True
hell:
End Function
answered Nov 14, 2014 at 16:56
iDevlopiDevlop
24.6k11 gold badges89 silver badges147 bronze badges
Here’s short sub without error handling that creates subdirectories:
Public Function CreateSubDirs(ByVal vstrPath As String)
Dim marrPath() As String
Dim mint As Integer
marrPath = Split(vstrPath, "")
vstrPath = marrPath(0) & ""
For mint = 1 To UBound(marrPath) 'walk down directory tree until not exists
If (Dir(vstrPath, vbDirectory) = "") Then Exit For
vstrPath = vstrPath & marrPath(mint) & ""
Next mint
MkDir vstrPath
For mint = mint To UBound(marrPath) 'create directories
vstrPath = vstrPath & marrPath(mint) & ""
MkDir vstrPath
Next mint
End Function
answered Mar 19, 2014 at 14:17
alexkovelskyalexkovelsky
3,7911 gold badge27 silver badges21 bronze badges
I know this has been answered and there were many good answers already, but for people who come here and look for a solution I could post what I have settled with eventually.
The following code handles both paths to a drive (like «C:Users…») and to a server address (style: «ServerPath..»), it takes a path as an argument and automatically strips any file names from it (use «» at the end if it’s already a directory path) and it returns false if for whatever reason the folder could not be created. Oh yes, it also creates sub-sub-sub-directories, if this was requested.
Public Function CreatePathTo(path As String) As Boolean
Dim sect() As String ' path sections
Dim reserve As Integer ' number of path sections that should be left untouched
Dim cPath As String ' temp path
Dim pos As Integer ' position in path
Dim lastDir As Integer ' the last valid path length
Dim i As Integer ' loop var
' unless it all works fine, assume it didn't work:
CreatePathTo = False
' trim any file name and the trailing path separator at the end:
path = Left(path, InStrRev(path, Application.PathSeparator) - 1)
' split the path into directory names
sect = Split(path, "")
' what kind of path is it?
If (UBound(sect) < 2) Then ' illegal path
Exit Function
ElseIf (InStr(sect(0), ":") = 2) Then
reserve = 0 ' only drive name is reserved
ElseIf (sect(0) = vbNullString) And (sect(1) = vbNullString) Then
reserve = 2 ' server-path - reserve "\Server"
Else ' unknown type
Exit Function
End If
' check backwards from where the path is missing:
lastDir = -1
For pos = UBound(sect) To reserve Step -1
' build the path:
cPath = vbNullString
For i = 0 To pos
cPath = cPath & sect(i) & Application.PathSeparator
Next ' i
' check if this path exists:
If (Dir(cPath, vbDirectory) <> vbNullString) Then
lastDir = pos
Exit For
End If
Next ' pos
' create subdirectories from that point onwards:
On Error GoTo Error01
For pos = lastDir + 1 To UBound(sect)
' build the path:
cPath = vbNullString
For i = 0 To pos
cPath = cPath & sect(i) & Application.PathSeparator
Next ' i
' create the directory:
MkDir cPath
Next ' pos
CreatePathTo = True
Exit Function
Error01:
End Function
I hope someone may find this useful. Enjoy!
answered Sep 15, 2017 at 14:15
Sascha L.Sascha L.
3472 silver badges6 bronze badges
This is a recursive version that works with letter drives as well as UNC. I used the error catching to implement it but if anyone can do one without, I would be interested to see it. This approach works from the branches to the root so it will be somewhat usable when you don’t have permissions in the root and lower parts of the directory tree.
' Reverse create directory path. This will create the directory tree from the top down to the root.
' Useful when working on network drives where you may not have access to the directories close to the root
Sub RevCreateDir(strCheckPath As String)
On Error GoTo goUpOneDir:
If Len(Dir(strCheckPath, vbDirectory)) = 0 And Len(strCheckPath) > 2 Then
MkDir strCheckPath
End If
Exit Sub
' Only go up the tree if error code Path not found (76).
goUpOneDir:
If Err.Number = 76 Then
Call RevCreateDir(Left(strCheckPath, InStrRev(strCheckPath, "") - 1))
Call RevCreateDir(strCheckPath)
End If
End Sub
answered Sep 19, 2019 at 2:33
1
Sub FolderCreate()
MkDir "C:Test"
End Sub
Bouke
1,5061 gold badge12 silver badges21 bronze badges
answered May 15, 2022 at 12:51
1
Sub MakeAllPath(ByVal PS$)
Dim PP$
If PS <> "" Then
' chop any end name
PP = Left(PS, InStrRev(PS, "") - 1)
' if not there so build it
If Dir(PP, vbDirectory) = "" Then
MakeAllPath Left(PP, InStrRev(PS, "") - 1)
' if not back to drive then build on what is there
If Right(PP, 1) <> ":" Then MkDir PP
End If
End If
End Sub
'Martins loop version above is better than MY recursive version
'so improve to below
Sub MakeAllDir(PathS$)
' format "K:firstfoldsecffold3"
If Dir(PathS) = vbNullString Then
' else do not bother
Dim LI&, MYPath$, BuildPath$, PathStrArray$()
PathStrArray = Split(PathS, "")
BuildPath = PathStrArray(0) & "" '
If Dir(BuildPath) = vbNullString Then
' trap problem of no drive : path given
If vbYes = MsgBox(PathStrArray(0) & "< not there for >" & PathS & " try to append to " & CurDir, vbYesNo) Then
BuildPath = CurDir & ""
Else
Exit Sub
End If
End If
'
' loop through required folders
'
For LI = 1 To UBound(PathStrArray)
BuildPath = BuildPath & PathStrArray(LI) & ""
If Dir(BuildPath, vbDirectory) = vbNullString Then MkDir BuildPath
Next LI
End If
' was already there
End Sub
' use like
'MakeAllDir "K:biljoanJohno"
'MakeAllDir "K:biljoanFredso"
'MakeAllDir "K:biltomwattom"
'MakeAllDir "K:bilherbwatherb"
'MakeAllDir "K:bilherbJim"
'MakeAllDir "biljoanwat" ' default drive
ZygD
21k39 gold badges77 silver badges98 bronze badges
answered Apr 2, 2017 at 20:38
Harry SHarry S
4616 silver badges5 bronze badges
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:TestExcel"
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:TOTNExamples"
In this example, the MKDIR statement would create a new directory called Examples under the c:TOTN directory.
For example:
MkDir "c:TOTNExamplesFiles"
In this example, the directory called Files would be created under the c:TOTNExamples 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:TOTNExcelExamples", vbDirectory)) = 0 Then MkDir "c:TOTNExcelExamples" End If
In this example, the code would first check to see if the c:TOTNExcelExamples directory exists. If it doesn’t exist, the MKDIR statement would create a new directory called Examples under the c:TOTNExcel directory.
Return to VBA Code Examples
MkDir Description
Used to create a new folder or directory.
Simple MkDir Examples
MkDir "D:MyFolder"
This creates a new folder “MyFolder” on the D drive.
If it already exists, it will occur a Run-time error ’75’: Path/File access error.
MkDir "MyFolder"
This creates a new folder “MyFolder” on the current folder(you can confirm the current folder using CurDir function).
MkDir Syntax
In the VBA Editor, you can type “MkDir(” to see the syntax for the MkDir Statement:
The MkDir statement contains an argument:
Path: A string expression representing a directory.
Examples of Excel VBA MkDir Function
MkDir "D:MyFolder
MkDir "D:MyFolderAA"
This creates a new folder “MyFolder” on the D drive, and then creates a new folder “AA” on the folder “D:MyFolder”.
MkDir "D:MyFolderBBCC"
In this case, if the parent folder “D:MyFolderBB” exists, the above code will create a new folder “CC” on the folder “D:MyFolderBB”.
But, if no exist, it will occur a Run-time error ’76’: Path not found.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!