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

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    Здесь обсуждаются вопросы по языку Visual Basic 1-6 (а так же по схожим языкам, как, например, PowerBASIC).
    Вопросы по Visual Basic .NET (это который входит в состав Visual Studio 2002/2003/2005/2008+, для тех, кто не в курсе) обсуждаются в разделе .NET.

    Обратите внимание:
    1. Прежде чем начать новую тему или отправить сообщение, убедитесь, что Вы не нарушаете правил форума!
    2. Обязательно воспользуйтесь поиском. Возможно, Ваш вопрос уже обсуждали. Полезные ссылки приведены ниже.
    3. Темы с просьбой выполнить какую-либо работу за автора в этом разделе не обсуждаются. Студенты, вам сюда: ПОМОЩЬ СТУДЕНТАМ!
    4. Используйте теги [ code=vba ] …текст программы… [ /code ] для выделения текста программы подсветкой.
    5. Помните, здесь телепатов нет. Формулируйте свой вопрос максимально грамотно и чётко: Как правильно задавать вопросы
    6. Запрещено отвечать в темы месячной (и более) давности, без веских на то причин.

    Полезные ссылки:
    user posted image FAQ Сайта user posted image FAQ Раздела user posted image Кладовка user posted image Наши Исходники user posted image API-Guide user posted image Поиск по Разделу user posted image MSDN Library Online user posted image Google


    Ваше мнение о модераторах: user posted image SCINER, user posted image B.V.

    >
    пустая ли папка?

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    07.08.02, 09:21

      Как узнать, пустая ли папка, или в ней есть какие-то файлы?


      Lion-K



      Сообщ.
      #2

      ,
      07.08.02, 21:12

        Воспользуйся MS Scripting Run Time (точно непомню как правильно она пишется. в VB меню [проект>ссылки])


        Magistr



        Сообщ.
        #3

        ,
        07.08.02, 21:19

          Senior Member

          ****

          Рейтинг (т): 1

          Для этого есть многоооо выходов из положения:


          Magistr



          Сообщ.
          #4

          ,
          07.08.02, 21:20

            Senior Member

            ****

            Рейтинг (т): 1

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


            Magistr



            Сообщ.
            #5

            ,
            07.08.02, 21:22

              Senior Member

              ****

              Рейтинг (т): 1

              ну вот даже сейчас тебе привиду наверно кусочек кода:

              public function GetEmptyDirectory(String path)
              on error resume next
              Kill path
              if err=0 then
              mkdir path
              GetEmptyDirectory=true
              else
              GetEmptyDirectory=false
              end if
              end function


              Magistr



              Сообщ.
              #6

              ,
              07.08.02, 21:26

                Senior Member

                ****

                Рейтинг (т): 1

                второй способ менее извращённый, хотя нет ещё более:
                создай контрол FileList а потом пиши:

                FileList.path=»C:MyFolder»
                on error resume next
                FileList.ListIndex=0

                public function GetEmptyDirectory(String path)
                FileList.path=»C:MyFolder»
                on error resume next
                FileList.ListIndex=0

                if err=0 then
                mkdir path
                GetEmptyDirectory=true
                else
                GetEmptyDirectory=false
                end if
                end function


                Magistr



                Сообщ.
                #7

                ,
                07.08.02, 21:30

                  Senior Member

                  ****

                  Рейтинг (т): 1

                  Ну и наконец самый лучший вариан — это поиск всех фалов в этой директории.

                  А уж как искать это ты посмотри по форуму, тут какой … всячины …. очень много :-)


                  Magistr



                  Сообщ.
                  #8

                  ,
                  07.08.02, 21:31

                    Senior Member

                    ****

                    Рейтинг (т): 1

                    Ой нет не всех достаточно только одного


                    ego



                    Сообщ.
                    #9

                    ,
                    07.08.02, 22:04

                      Вот набросал примерчик 8), правда не совсем уверен правильно ли он работает с корневыми каталогами  :-[. А уж про извращенность молчу  :-X

                      ExpandedWrap disabled

                        Option Explicit<br><br>Private Const INVALID_HANDLE_VALUE = -1<br>Private Const MAX_PATH = 260<br><br>Private Type FILETIME<br>        dwLowDateTime As Long<br>        dwHighDateTime As Long<br>End Type<br><br>Private Type WIN32_FIND_DATA<br>        dwFileAttributes As Long<br>        ftCreationTime As FILETIME<br>        ftLastAccessTime As FILETIME<br>        ftLastWriteTime As FILETIME<br>        nFileSizeHigh As Long<br>        nFileSizeLow As Long<br>        dwReserved0 As Long<br>        dwReserved1 As Long<br>        cFileName As String * MAX_PATH<br>        cAlternate As String * 14<br>End Type<br><br>Private Declare Function FindFirstFile Lib «kernel32» Alias «FindFirstFileA» (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long<br>Private Declare Function FindNextFile Lib «kernel32» Alias «FindNextFileA» (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long<br>Private Declare Function FindClose Lib «kernel32» (ByVal hFindFile As Long) As Long<br><br>Private Function есть_в_папке_файлы(Dir As String) As Boolean<br>    Dim fdata As WIN32_FIND_DATA<br>    Dim resval&<br>    Dim hfind&<br>    Dim i%<br>    <br>    hfind = FindFirstFile(Dir + «*.*», fdata)<br>    If hfind = INVALID_HANDLE_VALUE Then<br>        есть_в_папке_файлы = False<br>    Else<br>        If Len(Dir) = 2 Then    ‘корневой каталог<br>            есть_в_папке_файлы = True<br>        Else<br>            ‘пропускаем папки «.» и «..»<br>            For i = 1 To 2<br>                resval = FindNextFile(hfind, fdata)<br>            Next<br>            есть_в_папке_файлы = CBool(resval)<br>        End If<br>    End If<br>    FindClose hfind<br>End Function<br><br>Private Sub Command1_Click()<br>    If есть_в_папке_файлы(«c:мои документы») Then<br>        MsgBox «есть»<br>    Else<br>        MsgBox «нет»<br>    End If<br>End Sub


                      Lamerroot



                      Сообщ.
                      #10

                      ,
                      10.08.02, 18:04

                        Dim fso as Object
                        dim fold
                        Set fso = CreateObject(«Scripting.FileSystemObject»)
                        Set fold = fso.GetFolder(«Path»)
                        if fold.file.count = 0 then msgbox «Папка пуста!»


                        Lamerroot



                        Сообщ.
                        #11

                        ,
                        10.08.02, 18:05

                          Dim fso as Object
                          dim fold
                          Set fso = CreateObject(«Scripting.FileSystemObject»)
                          Set fold = fso.GetFolder(«Path»)
                          if fold.files.count = 0 then msgbox «Папка пуста!»


                          TurboMent



                          Сообщ.
                          #12

                          ,
                          28.07.03, 20:31

                            Извращенцы  :-/

                            Вот код:

                            Public Function GetEmptyDirectory(path As String) As Boolean
                            Dim a As String
                            a = Dir(path)
                            If a = «» Then
                            GetEmptyDirectory = True
                            Else
                            GetEmptyDirectory = False
                            End If
                            End Function

                            0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                            0 пользователей:

                            • Предыдущая тема
                            • Visual Basic: Общие вопросы
                            • Следующая тема

                            Рейтинг@Mail.ru

                            [ Script execution time: 0,0601 ]   [ 16 queries used ]   [ Generated: 14.04.23, 17:10 GMT ]  

                            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

                            Доброго времени суток, Уважаемые!
                            Столкнулся с задачей похожей на вышеизложенную, но с маленьким нюансом.
                            Суть такова:
                            Необходимо создать некое подобие базы данных. В идеале должно выглядеть как папка с названием, предположим «Объект», в котором будет Excelевский файл и папка «Фотографии».
                            В Excelевском файле будет некая информация и два столбца с данными (столбцы будут содержать данные типа 1,2,3..n и 1-2,2-3,3-4…m). А в папке «Фотографии» будут соответственно папки с названиями «1»,»2″,»3″…»n», «1-2″,»2-3″…»m». (как сделать такую вещь с помощью вышеизложенного варианта я понял) Идем дальше. Нужно сделать так, что бы при нажатии на ячейку с данными, например «1», открывалась папка «1»?
                            Вариант с гиперссылками пробовал. Вот в таком виде » =ГИПЕРССЫЛКА(«D:ОбъектФотографии»&A7&»») » в ячейке А7 стоит число 1. Потом протянув ячейку вниз получаем ссылки на А8,А9…и т.д. Способ хорош если эта база стационарна и находится в одном месте. При перемещении папки «Объект» в другую директорию, в первой ячейке где гиперссылка нужно вручную прописать новый путь, а потом протянуть по всему столбцу. Это очень неудобно, потому как планируется довольно частое копирование папки Объект другим пользователям. В каждом файле порядка 300 строк, а папок «Объект» будет в районе сотни…
                            И в итоге нужно что бы при перемещении папки «Объект» ссылки не сбивались и не нужно было вручную править пути.
                            Если у кого-то будут идеи и решения по этому поводу, буду премного благодарен!!!
                            Только если можно поподробнее…а то я в макросах…не очень…

                            Добавлено через 1 час 37 минут
                            Все-таки я допустил неточность…
                            Если сделать обычную гиперссылку на папку «1» из ячейки с данными 1, то при условии перемещения папки «Объект», содержащей Экселевский файл и папку «Фотографии», гиперссылки сохраняются. Проблема только в том, что бы автоматизировать присвоение гиперссылок ячейкам с другими данными (на подобии как » =ГИПЕРССЫЛКА(«D:ОбъектФотографии»&A7&»») » и протянуть вниз). Ибо при наличии порядка 300 ячеек с данными, присваивать каждой гиперссылку вручную… а папок «Объект» порядка сотни….

                            Добавлено через 22 минуты
                            И еще один вопрос, что нужно изменить в коде макроса по созданию папок, что бы, например папка Фотографии и вложенные в нее папки с именами из Экселевского файла, создавались при запуске макроса в той директории где в данный момент находится папка?

                            Мой код должен пройти через папки / подпрограммы и определить, есть ли там какой-либо файл.

                            У меня 2 вопроса:

                            1. Я не получаю отзывов, если в определенных папках НЕТ папок / подписок. Конкретный случай: если он обнаруживает файлы (не папки), предположим, что в нем есть какие-то файлы (например, Excel), программа говорит «Пустая папка»?

                            2. В диалоговом окне «Открыть окно» для выбора папки, если я нажму «Отмена», появится всплывающее окно с сообщением: «Папка не пуста..блабла …»

                            Sub Button1_click()
                            
                            Dim FileSystem As Object
                            Dim HostFolder As String
                            Dim Answer As String
                            Dim fs, strFolderPath, oFolder
                            
                            ' *** Folder with Files to perform an action ***
                            HostFolder = GetSourceFolder()
                            
                            Application.ScreenUpdating = False
                            Application.Calculation = xlCalculationManual
                            
                            ' *** This is your folder to define ***
                                Set fs = CreateObject("Scripting.FileSystemObject")
                                strFolderPath = Application.ActiveWorkbook.Path
                                Set oFolder = fs.getfolder(strFolderPath)
                                    If (oFolder.SubFolders.Count = 0) Then
                            
                            ' *** If folder is empty/full message ***
                            ' * Folder is Empty *
                                   MsgBox "Folder is empty!", vbOKOnly + vbInformation, "Information!"
                            
                                    Else
                            ' * Folder isn't empty *
                                   Answer = MsgBox("Folder not empty! Proceed with Macro?", vbYesNo + vbInformation + vbDefaultButton1, "Information!")
                                    If Answer = vbNo Then Exit Sub
                                End If
                            
                            Set fs = Nothing
                            
                            Set FileSystem = CreateObject("Scripting.FileSystemObject")
                                Dim targetFolder As String
                                targetFolder = GetTargetFolder()
                            
                                DoFolder FileSystem.getfolder(HostFolder)
                            
                                Application.ScreenUpdating = True
                                Application.Calculation = xlCalculationAutomatic
                            
                            End Sub
                            
                            
                            Function GetSourceFolder() As String
                                Dim fldr As FileDialog
                                Dim sItem As String
                                Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
                                With fldr
                                    .Title = "Select Source Folder"
                                    .AllowMultiSelect = False
                                    .InitialFileName = Application.DefaultFilePath
                                    If .Show <> -1 Then GoTo NextCode
                                    sItem = .SelectedItems(1)
                                End With
                            NextCode:
                                GetSourceFolder = sItem
                                Set fldr = Nothing
                            End Function
                            
                            Function GetTargetFolder() As String
                                Dim fldr As FileDialog
                                Dim sItem As String
                                Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
                                With fldr
                                    .Title = "Select Output Folder"
                                    .AllowMultiSelect = False
                                    .InitialFileName = Application.DefaultFilePath
                                    If .Show <> -1 Then GoTo NextCode
                                    sItem = .SelectedItems(1)
                                End With
                            NextCode:
                                GetTargetFolder = sItem
                                Set fldr = Nothing
                            End Function
                            

                            1 ответ

                            Лучший ответ

                            Если вы хотите сделать отдельную процедуру для выбора папки, вам необходимо определить, выбрал ли что-либо пользователь. Вы можете использовать тип возвращаемого значения Boolean функции как результат действия и строку для исходной папки, которая передается по ссылке, которая будет заполнена, если папка выбрана пользователем. Вот базовый код:

                            Sub Test()
                            
                                Dim sourceFolder As String
                            
                                '// Usage
                                If Not GetSourceFolder(sourceFolder) Then
                                    MsgBox "No folder selected", vbExclamation
                                    Exit Sub
                                End If
                            
                                '// Go on with your code
                            
                            End Sub
                            
                            Function GetSourceFolder(ByRef sourceFolder As String) As Boolean
                                '// By default function will return False
                                With Application.FileDialog(msoFileDialogFolderPicker)
                                    If .Show Then
                                        sourceFolder = .SelectedItems(1)
                                        GetSourceFolder = True
                                    End If
                                End With
                            End Function
                            


                            0

                            JohnyL
                            27 Ноя 2018 в 12:05

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