Vba excel создать директорию

Создание, копирование, перемещение и удаление папок в 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.
VBA MkDir Function

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.
VBA MkDir Function

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.
VBA MkDir Function

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.
VBA MkDir Function

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?

Martijn Pieters's user avatar

asked May 29, 2012 at 17:23

Matt Ridge's user avatar

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

Martin's user avatar

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 Holtzman's user avatar

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

Leandro Jacques's user avatar

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's user avatar

ZygD

21k39 gold badges77 silver badges98 bronze badges

answered Mar 13, 2014 at 18:50

Chandan Kumar's user avatar

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

SandPiper's user avatar

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's user avatar

ZygD

21k39 gold badges77 silver badges98 bronze badges

answered Oct 23, 2019 at 7:27

Zoynels's user avatar

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

Community's user avatar

answered Jan 15, 2015 at 4:13

Brett's user avatar

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

mindgutter's user avatar

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

iDevlop's user avatar

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

Marcus Mangelsdorf's user avatar

answered Mar 19, 2014 at 14:17

alexkovelsky's user avatar

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.'s user avatar

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

Rubber Toe's user avatar

1

Sub FolderCreate()
    MkDir "C:Test"
End Sub

Bouke's user avatar

Bouke

1,5061 gold badge12 silver badges21 bronze badges

answered May 15, 2022 at 12:51

Tarun Singh's user avatar

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's user avatar

ZygD

21k39 gold badges77 silver badges98 bronze badges

answered Apr 2, 2017 at 20:38

Harry S's user avatar

Harry SHarry S

4616 silver badges5 bronze badges

totn Excel Functions


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.

В этом учебном материале вы узнаете, как использовать Excel оператор MKDIR с синтаксисом и примерами.

Описание

Оператор MKDIR позволяет создать новую папку или каталог.
Функция MKDIR — это встроенная в Excel функция, которая относится к категории функций файлов/каталогов. Её можно использовать как функцию VBA в Excel.
В качестве функции VBA вы можете использовать эту функцию в коде макроса, который вводится через редактор Microsoft Visual Basic Editor.

Синтаксис

Синтаксис оператора MKDIR в Microsoft Excel:

MkDir path

Аргументы или параметры

path
Папка или каталог для создания.

Возвращаемое значение

Оператор MKDIR не возвращает значение, а скорее создает новую папку или каталог.
Если путь представляет собой сложную структуру каталогов, каталоги высокого уровня должны уже существовать, иначе оператор MKDIR вызовет ошибку, например, если вы выполнили следующий код:

Каталог c:Test уже должен существовать. Оператор MKDIR будет пытаться создать каталог Excel только в каталоге c:Test. Сам каталог c:Test не будет создан.

Применение

  • Excel для Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 для Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Тип функции

  • Функция VBA

Пример (как оператор VBA)

Оператор MKDIR может использоваться только в коде VBA в Microsoft Excel.
Давайте взглянем на некоторые примеры функций оператора MKDIR, чтобы понять, как использовать оператор MKDIR в коде Excel VBA:

MkDir «c:ExcelExamples»

В этом примере оператор MKDIR создал новый каталог с именем Examples в каталоге c:Excel, например:

MkDir «c:ExcelExamplesFiles»

В этом примере каталог с именем Files будет создан в каталоге c:ExcelExamples.

Часто задаваемые вопросы

Вопрос: Я не уверен, существует ли уже конкретный каталог.
Если он не существует, я бы хотел создать его с помощью кода VBA. Как я могу это сделать?

Ответ: Вы можете проверить, существует ли каталог, используя приведенный ниже код VBA:

If Len(Dir(«c:TESTExcelExamples», vbDirectory)) = 0 Then

   MkDir «c:TESTExcelExamples»

End If

В этом примере код сначала проверяет, существует ли каталог c:TESTExcelExamples.
Если он не существует, оператор MKDIR создаст новый каталог с именем Examples в каталоге c:TESTExcel.

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!
vba save as

Learn More!

Creating, deleting and renaming folders is a common requirement when automating processes with VBA.  The code snippets below should be sufficient to complete the most common folder tasks.

All the code examples below use the built-in Dir() function and its derivatives.  The File System Object methods are not covered in this post but will be covered at a future point.

Check if a folder exists

Referencing a folder which does not exist will result in an error, therefore it is often necessary to check if a folder exists before carrying out any other actions.

'Check if a folder exists
Dim folderPath As String
folderPath = "C:UsersmarksDocumentsFolder"

If Dir(folderPath, vbDirectory) <> "" Then

    'Insert action for if the folder exists
    'This example prints to the immediate window
    Debug.Print folderPath & " exists."

Else

    'Insert actions if the folder does not exist
    'This example prints to the immediate window
    Debug.Print folderPath & " does not exist."

End If

vbDirectory is the attribute of a folder.  The code above can be adapted to check for other types of files too.

VBA Name of attribute Enumerator Description
vbNormal 0 Files with no attributes (default setting)
vbReadOnly 1 Read-only files
vbHidden 2 Hidden files
vbSystem 4 System files
vbVolume 8 Volume label
vbDirectory 16 Directories

For checking folder existence within another procedure, it is often easier to have a reusable function, which can be called upon when required.

'Reusable function to check if a folder exists
Function doesFolderExist(folderPath) As Boolean

DoesFolderExist = Dir(folderPath, vbDirectory) <> ""

End Function

The following VBA code calls the doesFolderExist function from above and prints True (the folder exists) or False (the folder does not exist) to the Immediate window.

'Call the reusable function to check for folder existence
Debug.Print doesFolderExist("C:UsersmarksDocumentsFolder")

The following VBA code calls the doesFolderExist function from above for use within an If statement.

'Check if a folder exists calling the doesFolderExist function
Dim folderPath As String
folderPath = "C:UsersmarksDocumentsFolder"

If doesFolderExist(folderPath) = True Then

    'Insert action for if the folder exists
    'This example prints to the immediate window
    Debug.Print folderPath & " exists."

Else

    'Insert actions if the folder does not exist
    'This example prints to the immediate window
    Debug.Print folderPath & " does not exist."

End If

Create a new folder

The VBA code below will create a new folder.  If the folder already exists, it will not overwrite it, but it will display an error.  The function will only create the last folder in the file path, all the parent folders must already exist.

'Create a new folder
MkDir "C:UsersmarksDocumentsNew folder"

The avoid an error, the code below will check if a folder exists before trying to create it.

'Create a folder if it does not already exist, if it does, do nothing 
Dim folderPath As String
folderPath = "C:UsersmarksDocumentsNew Folder"

'Check if the folder exists
If Dir(folderPath, vbDirectory) = "" Then

    'Folder does not exist, so create it
    MkDir folderPath

End If

As the Dir() function will only create a single folder, the code below loops through the individual folder names in the path and calls the Dir() function to create any missing folders and subfolders.

'Create all the folders in a folder path
Dim folderPath As String
Dim individualFolders() As String
Dim tempFolderPath As String
Dim arrayElement As Variant

'The desired folder path
folderPath = "C:UsersmarksDocumentsNew FolderNew FolderNew FolderNew Folder"

'Split the folder path into individual folder names
individualFolders = Split(folderPath, "")

'Loop though each individual folder name
For Each arrayElement In individualFolders

'Build string of folder path
    tempFolderPath = tempFolderPath & arrayElement & ""
 
    'If folder does not exist, then create it
    If Dir(tempFolderPath, vbDirectory) = "" Then
 
        MkDir tempFolderPath
 
     End If
 
Next arrayElement

Delete a folder

The RmDir function will delete a folder.  However, it is limited as it will only delete an empty folder.  All the files within the folder will need to be deleted first.  Using the File System Object method (which is not covered in this post) it is possible to delete folders and their contents.

'Delete a folder
Dim folderPath As String
folderPath = "C:UsersmarksDocumentsDelete Folder"

'Ensure the folder path as a "" at the end of the string
'Required for deleting the files using wildcards
If Right(folderPath, 1) <> "" Then folderPath = folderPath & ""

'Use wildcards to delete all the files in the folder
Kill folderPath & "*.*"

'Delete the now empty folder
RmDir folderPath

If the folder does not exist the RmDir function will display an error.  Refer to the first section of this post to check for existence

Rename a folder

The VBA code below will re-name a folder, and even move the contents of the entire folder to another location.

'Rename a folder
Name "C:UsersmarksDocumentsFolder" As "C:UsersmarksDocumentsRenamed Folder"

To use this example code, it may be necessary to check if the old folder name exists and the new folder name does not exist.


Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

  • Функции WinAPI
  • Средства Windows
  • Работа с файлами

Как известно, VBA-функция MkDir может создать только папку в существующем каталоге (папке).

 
Например, код MkDir «C:Папка» отработает корректно в любом случае (создаст указанную папку),
а код MkDir «C:ПапкаПодпапкаКаталог» выдаст ошибку Run-time error ’76’: Path not found
(потому что невозможно создать каталог Подпапка в несуществующем ещё каталоге Папка)

 
Можно, конечно, использовать несколько функций MkDir подряд — но это усложняет код.

 
Самый простой способ решения проблемы — использование WinAPI-функции SHCreateDirectoryEx, которая может создать все нужные папки и подпапки за один запуск.

Declare Function SHCreateDirectoryEx Lib "shell32" Alias "SHCreateDirectoryExA" _
                                     (ByVal hwnd As Long, ByVal pszPath As String, _
                                      ByVal psa As Any) As Long
 
 
Sub CreateFolderWithSubfolders(ByVal ПутьСоздаваемойПапки$)
    ' функция получает в качестве параметра путь к папке
    ' если такой папки ещё нет - она создаётся
    ' может создаваться сразу несколько подпапок
    If Len(Dir(ПутьСоздаваемойПапки$, vbDirectory)) = 0 Then    ' если папка отсутствует
        SHCreateDirectoryEx Application.hwnd, ПутьСоздаваемойПапки$, ByVal 0&    ' создаём путь
    End If
End Sub

Пример использования функции SHCreateDirectoryEx:

Sub ПримерИспользованияCreateFolderWithSubfolders()
    ' этот макрос создаст на диске C папку "Создаваемая папка",
    ' в ней - подпапку "Подпапка", а в последней - подпапку 1234
    Путь = "C:Создаваемая папкаПодпапка1234"
 
    CreateFolderWithSubfolders Путь
End Sub
  • 69885 просмотров

Не получается применить макрос? Не удаётся изменить код под свои нужды?

Оформите заказ у нас на сайте, не забыв прикрепить примеры файлов, и описать, что и как должно работать.

Like this post? Please share to your friends:
  • Vba excel создание файла word
  • Vba excel создание ссылки
  • Vba excel создание списков
  • Vba excel создание списка
  • Vba excel создание пользовательской формы