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.

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
  • 69884 просмотра

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

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

В этом учебном материале вы узнаете, как использовать 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.

 

Коллеги, Добрый день! Помогите решить задачку. Из столбца G или H взять название строки, и создать папку с таким же именем например на рабочем столе . Папки  нужны для каждой строки.  

 

tolstak

Пользователь

Сообщений: 471
Регистрация: 01.08.2017

#2

05.09.2017 12:53:34

tairov-vladimir,

посмотрите тут.

Upd. Простите, не внимательно прочитал пост, там немного другое :)
Вот код, создающий папки в директории где лежит файл:

Код
Sub createFolders()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FilesystemObject")
    For Each el In Range([G2], [G1].Offset([A2].End(xlDown).Row - 1, 0))
        If Not fso.FolderExists(ThisWorkbook.Path & "" & el.Value) Then
            fso.CreateFolder (ThisWorkbook.Path & "" & el.Value)
        End If
    Next
End Sub

Модификация для создания папок на рабочем столе:

Код
Sub createFoldersonDesktop()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FilesystemObject")
    For Each el In Range([G2], [G1].Offset([A2].End(xlDown).Row - 1, 0))
        If Not fso.FolderExists(Environ("USERPROFILE") & "Desktop" & el.Value) Then
            fso.CreateFolder (Environ("USERPROFILE") & "Desktop" & el.Value)
        End If
    Next
End Sub

Прикрепленные файлы

  • Таблица учета v.2 (1).xlsm (41.34 КБ)

Изменено: tolstak05.09.2017 13:08:38

In GoTo we trust

 

Скажите а есть возможность создавать папки по указанному пути??

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#4

05.09.2017 13:39:35

Код
    sFldr = Path  ' путь к папке
    If Dir(sFldr, vbDirectory) = "" Then MkDir sFldr ' создаем, если нет
 

vikttur, то есть в коде от tolstak меняем первые две строки?

 

tolstak

Пользователь

Сообщений: 471
Регистрация: 01.08.2017

#6

05.09.2017 13:49:56

Код
Sub createFolders()
    Dim fso As Object
    sFldr = "C:ВашаПапка"  ' путь к папке
    If Dir(sFldr, vbDirectory) = "" Then MkDir sFldr ' создаем, если нет
    Set fso = CreateObject("Scripting.FilesystemObject")
    For Each el In Range([G2], [G1].Offset([A2].End(xlDown).Row - 1, 0))
        If Not fso.FolderExists(sFldr  & el.Value) Then
            fso.CreateFolder (sFldr  & el.Value)
        End If
    Next
End Sub

Изменено: tolstak05.09.2017 13:50:04

In GoTo we trust

 

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

 

tolstak

Пользователь

Сообщений: 471
Регистрация: 01.08.2017

#8

05.09.2017 14:43:13

tairov-vladimir,

Код
Sub createFolders()
    Dim fso As Object, el As Range
    ' Выбор ячейки с названием папки
    Set el = Application.InputBox( _
        Prompt:="Выберите строку с названием папки", _
        Title:="Строка с названием", _
        Default:=Intersect([G:G], Selection.EntireRow).Address, _
        Type:=8)
    
    ' Папка для создания по умолчанию
    sFldr = "C:UsersuserDesktopЕРЕМИАСНовая папка"
    ' Возмоожность изменить папку
    sFldr = InputBox( _
        Prompt:="Адрес сохранения", _
        Title:="Куда сохранять?", _
        Default:=sFldr)
    If Not el Is Nothing And sFldr <> "" And el.Value <> "" Then
        Set el = Intersect([G:G], el)
        If Dir(sFldr, vbDirectory) = "" Then MkDir sFldr ' создаем, если нет
        Set fso = CreateObject("Scripting.FilesystemObject")
        If Not fso.FolderExists(sFldr & el.Value) Then
            fso.CreateFolder (sFldr & el.Value)
        End If
    Else
        MsgBox "Папка или название файла не выбраны.", vbCritical
    End If
End Sub

Прикрепленные файлы

  • Таблица учета v.2 (1) (1).xlsm (45.69 КБ)

In GoTo we trust

 

Здравствуйте.
При выполнении макроса из сообщения #8 возникает ошибка : Run-time error 76 Path not found
Debug показывает что ошибка в строке 19.
Подскажите, как исправить, пожалуйста.

 

Имеется в виду путь из строки 11?

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

Path not found — нет такого пути.
Строка 19 — создаем папку, если по указанному пути нет папки с таким именем.
sFldr — недопустимый путь. Проверьте переменную.

 

tolstak

Пользователь

Сообщений: 471
Регистрация: 01.08.2017

#12

04.10.2017 14:05:19

DmitriyBastr, вероятно, у Вас не создана корневая папка. В сообщении #8 папка по пути «C:UsersuserDesktopЕРЕМИАСНовая папкаЦ-108-30.08.3018-М-4» будет создана, если существует папка «C:UsersuserDesktopЕРЕМИАСНовая папка».

Цитата
Имеется в виду путь из строки 11?

Да, или путь, указанный в всплывающем диалоге «Куда сохранять»

Изменено: tolstak04.10.2017 14:12:52

In GoTo we trust

 

Прописал в коде свой путь «C:UsersuserDesktop2»
Теперь выдает ошибку в строке 21
Object variable or With block variable not set

 

tolstak

Пользователь

Сообщений: 471
Регистрация: 01.08.2017

DmitriyBastr, пропишите с последним символом — слешем — «C:UsersuserDesktop2«, должно помочь.

 

«» есть, я его в сообщении просто не написал…

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#16

04.10.2017 14:43:07

Ну, диск С у Вас, надеюсь, есть? :)
Проверьте так:

Код
sFldr = "C:Новая папка"
 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#17

04.10.2017 14:45:01

Цитата
DmitriyBastr написал:
«» есть, я его в сообщении просто не написал

Почему не писали? Чтобы проверить, заметят ли форумчане эту ошибку?

 

Всё… Разобрался… Заработало
Большое спасибо!!!

 

… Все-таки продолжу…
Код из сообщения #8 работает. Но он создает папку только с именем из 7-го столбца, а не из любой выбранной ячейки, как было написано в сообщении #7. Что с этим можно сделать?

 

tolstak

Пользователь

Сообщений: 471
Регистрация: 01.08.2017

#20

04.10.2017 15:52:53

DmitriyBastr, уберите из кода эту строку:

Код
Set el = Intersect([G:G], el)

In GoTo we trust

 
 

argyman

Пользователь

Сообщений: 45
Регистрация: 20.04.2015

#22

22.05.2019 11:43:28

tolstak, Добрый день! при запуске этого макроса, Excel зависает минут на 5, это нормально? Помогите пожалуйста

Код
Sub createFolders()
    Dim fso As Object
    sFldr = "C:ВашаПапка"  ' путь к папке
    If Dir(sFldr, vbDirectory) = "" Then MkDir sFldr ' создаем, если нет
    Set fso = CreateObject("Scripting.FilesystemObject")
    For Each el In Range([G2], [G1].Offset([A2].End(xlDown).Row - 1, 0))
        If Not fso.FolderExists(sFldr  & el.Value) Then
            fso.CreateFolder (sFldr  & el.Value)
        End If
    Next
End Sub

Прикрепленные файлы

  • пример_сохр.xlsm (12.51 КБ)

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Для начала проверьте букву «С» в ячейке А1

 

argyman

Пользователь

Сообщений: 45
Регистрация: 20.04.2015

Юрий М, спасибо исправил, но макрос все равно зависает на минут 5

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Так у Вас в примере цикл перебирает все ячейки столбца, а это 1 048 576 строк.

 

junato

Пользователь

Сообщений: 4
Регистрация: 28.01.2018

Добрый день.

Кто может помочь на форуме нашел, что кто-то уже организовывал создание подпапок но только до 2-го уровня. Так как я не владею VBА на должном уровне помогите пожалуйста чтобы создавались папки до 4 уровня. Я привел примеры.  

 

Ян Андреевич

Пользователь

Сообщений: 1
Регистрация: 10.08.2022

#27

10.08.2022 17:21:05

Здравствуйте, не хотелось плодить дополнительных тем, поэтому  пишу здесь:
По примеру решений на форуме, захотел сделать макрос, который создает папку исходя из данных из строк в exel.

при  этом важная задача:  привязывать создаваемые папки к региону .  а не сохранять в рандомных местах.
но выкидывает ошибку.
похоже на ошибку пунктуации.

Наименование создаваемой папки формируется из столбца 3,2 , 4 и 5.  

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

Прикрепленные файлы

  • сохранение.xlsm (24.71 КБ)

Никто и не говорил про необходимость проверять возникновение ошибок…
Я в подобных случаях использую примерно такие конструкции:

Visual Basic
1
2
3
4
5
6
7
8
9
Private Sub Workbook_Open()
    On Error Resume Next: Err.Clear
    Путь = "C:Tempимя папки"
    If Len(Dir(Путь)) = 0 And True Or Day(Date) = 28 Then MkDir (Путь)
    If Err Then MsgBox "Не удалось создать папку", vbCritical: Exit Sub
    ThisWorkbook.SaveAs Путь & ИмяФайла
    If Err Then MsgBox "Не удалось сохранить файл!", vbCritical: Exit Sub
    ' и т.д.
End Sub

В любом случае, всех возможных ошибок не предусмотришь…

А вообще повторюсь (в какой-то соседней теме уже поднимался вопрос обработки ошибок), ошибку, если есть такая возможность, лучше избегать, это пишут во всех книгах и это говорят все мои знакомые гуру. Ничего страшного в паре «лишних» строк кода нету!

Ладно, если было бы достаточно пары строк…
В случаях, когда любое из последовательных действий может вызвать ошибку, я сам использую подобные конструкции (например, в цикле открываем файл excel, в нем ищем определённый лист, на нём — некую таблицу, и т.д.)

В данном же случае, ИМХО, вполне достаточно и On Error Resume Next

А начинающим даже полезно.

Не спорю, полезно.
Но, если человеку нужен ОДИН работающий макрос, и он в будущем не намерен углубляться в дебри программирования, — его вполне устроит и «урезанный» вариант макроса.

Зачем пытаться предусмотреть все ошибки, не зная, на каких данных и оборудовании будет работать этот макрос?
Бывает, я пишу на форум макросы из 2 строк: первая — это On Error Resume Next, вторая — длинная строка типа этого:

Visual Basic
1
MsgBox ActiveSheet.UsedRange.Find("текст").Next.Resize(3).Find("текст2").EntireRow.Cells(1)

Для своих нужд, я, конечно, такое бы не написал, но просящих помощи форумчан такие варианты более чем устраивают.

Понравилась статья? Поделить с друзьями:
  • Vba excel создание нового листа
  • Vba excel создание листа с именем
  • Vba excel создание книги с одним листом
  • Vba excel создание класса
  • Vba excel создание динамического массива