Vba excel удалить папок

Хитрости »

28 Июль 2017              20503 просмотров


Предположим, что ежедневно во временную папку поступают файлы отчетов от филиалов. Они могут собираться из почты кодом вроде такого: Сохранить вложения из Outlook в указанную папку или добавляться в папку иными средствами. Далее Вы собираете данные из этих файлов неким кодом(вроде этого — Как собрать данные с нескольких листов или книг?). Но с каждым днем файлов все больше и больше и приходится заходить в папку и руками чистить её от лишних файлов, чтобы при сборе данных не приходилось каждый раз искать и отбирать только новые файлы.
Если надо удалять только конкретные файлы(например только файлы Excel, содержащие в имени слово «отчет»), то можно использовать такой код:

Sub Remove_AllFilesFromFolder()
    Dim sFolder As String, sFiles As String
    'диалог запроса выбора папки с файлами
    'подробнее про диалоги выбора папки или файла:
    '       http://www.excel-vba.ru/chto-umeet-excel/dialogovoe-okno-vybora-fajlovpapki/
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = False Then Exit Sub
        sFolder = .SelectedItems(1)
    End With
    sFolder = sFolder & IIf(Right(sFolder, 1) = Application.PathSeparator, "", Application.PathSeparator)
    'отбирать только файлы Excel, содержащие в имени слово "отчет"
    sFiles = Dir(sFolder & "*отчет*.xls*")
    'цикл по всем файлам в папке
    On Error Resume Next
    Do While sFiles <> ""
        'удаляем файл
        Kill sFolder & sFiles
        If Err.Number = 70 Then
            MsgBox "Невозможно удалить файл '" & sFiles & "'. Возможно файл открыт в другой программе или нет прав на удаление", vbCritical, "www.excel-vba.ru"
            Err.Clear
        End If
        'на всякий случай передаем управление системе,
        'чтобы дождаться удаления
        DoEvents
        'получаем имя следующего файла в папке
        sFiles = Dir
    Loop
End Sub

Чтобы удалять полностью все файлы в папке(а не только файлы Excel), а саму папку оставить, то строку sFiles = Dir(sFolder & «*отчет*.xls*») надо записать так: sFiles = Dir(sFolder & «*»)

Если необходимо удалять файлы по дате создания/изменения(например, только файлы, созданные раньше 01.03.2017), то можно использовать такой код:

Sub Remove_FilesFromFolder_AfterDate()
    Dim sFolder As String, sFiles As String
    Dim dd As Date, dKill As Date
 
    'задаем дату. Если файл был создан/изменен до этой даты - он будет удален
    dKill = CDate("01.03.2017") 'можно задать проще: dKill = #3/1/2017#
    'диалог запроса выбора папки с файлами
    'подробнее про диалоги выбора папки или файла:
    '       http://www.excel-vba.ru/chto-umeet-excel/dialogovoe-okno-vybora-fajlovpapki/
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = False Then Exit Sub
        sFolder = .SelectedItems(1)
    End With
    sFolder = sFolder & IIf(Right(sFolder, 1) = Application.PathSeparator, "", Application.PathSeparator)
    sFiles = Dir(sFolder & "*")
    'цикл по всем файлам в папке
    On Error Resume Next
    Do While sFiles <> ""
        'получаем дату создания или изменения файла
        dd = FileDateTime(sFolder & sFiles)
        'если дата файла меньше заданной для удаления(был создан раньше)
        If dd < dKill Then
            'удаляем файл
            Kill sFolder & sFiles
            If Err.Number = 70 Then
                MsgBox "Невозможно удалить файл '" & sFiles & "'. Возможно файл открыт в другой программе или нет прав на удаление", vbCritical, "www.excel-vba.ru"
                Err.Clear
            End If
            'на всякий случай передаем управление системе,
            'чтобы дождаться удаления
            DoEvents
        End If
        'получаем имя следующего файла в папке
        sFiles = Dir
    Loop
End Sub

Если необходимо всегда удалять файлы, дата создания которых раньше текущей, то строку dKill = CDate(«01.03.2017») нужно заменить на такую: dKill = Date. Если удалить надо файлы недельной давности, то: dKill = Date-7


Если же необходимо удалить папку полностью, а не только файлы в ней, то лучше использовать такой код:

Sub RemoveFolderWithContent()
    Dim sFolder As String, sFiles As String
    'диалог запроса выбора папки на удаление
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = False Then Exit Sub
        sFolder = .SelectedItems(1)
    End With
    sFolder = sFolder & IIf(Right(sFolder, 1) = Application.PathSeparator, "", Application.PathSeparator)
    'путь к папке можно задать статично, если он заранее известен и не изменяется
    '    sFolder = "C:tempЕжедневные отчеты10072017" 'путь к папке, которую надо удалить
    Shell "cmd /c rd /S/Q """ & sFolder & """"
End Sub

Этот код удалить папку вместе со всеми файлами буквально за секунду.
Вообще в VBA есть специальная команда для удаления директорий(папок) RmDir. Но она способна удалить только пустую папку, поэтому редко когда можно найти её практическое применение. Если в файле есть хоть один файл то команда RmDir выдаст ошибку ’75’ — File/Path access error.

Так же см.:
Как средствами VBA переименовать/переместить/скопировать файл
Просмотреть все файлы в папке
Как собрать данные с нескольких листов или книг?
Как удалить книгу из самой себя


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

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

Return to VBA Code Examples

This short tutorial will demonstrate how to use DeleteFolder method of the FileSystemObject.

Delete Folder with VBA FileSystemObject

This lesson uses the FileSystemObject. In order to use it, you will need to set a reference to the VB script run-time library. See here for more information.

Deleting folders is easy using DeleteFolder method of the FileSystemObject.

Sub FSODeleteFolder()
    Dim FSO As New FileSystemObject
    Set FSO = CreateObject("Scripting.FileSystemObject")

    FSO.DeleteFolder "C:TestFolder", False

End Sub

If the optional ’force’ part at the end of the FSO.DeleteFolder line is set to True, folders with the read-only attribute set can be also deleted.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

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

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

Check if a folder exists

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

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

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

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

Else

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

End If

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

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

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

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

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

End Function

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

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

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

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

If doesFolderExist(folderPath) = True Then

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

Else

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

End If

Create a new folder

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

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

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

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

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

    'Folder does not exist, so create it
    MkDir folderPath

End If

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

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

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

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

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

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

Delete a folder

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

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

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

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

'Delete the now empty folder
RmDir folderPath

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

Rename a folder

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

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

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


Headshot Round

About the author

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

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

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


Do you need help adapting this post to your needs?

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

But, if you’re still struggling you should:

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

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

bodeaux

3 / 3 / 0

Регистрация: 20.07.2012

Сообщений: 27

1

Создание и удаление папки

23.07.2012, 14:45. Показов 16218. Ответов 6

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

требуется создать папку Fold в активной директории CurDir, а если папка с таким именем
Уже существует — удалить ее, а затем создать снова

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
Function createMainDir() As String
 
  Dim path As String
  path = CurDir + "Fold"
  
  If Not (Dir(path) = "") Then
    RmDir (path)
  End If
  
  MkDir (path)
  createMainDir = path
  
End Function

при первом запуске функция создает нужную папку,
при втором запуске (папка не удалена) функция останавливает работу с ошибкой
Path access error в точке MkDir (path)

почему существующая папка Fold не удаляется?



0



аналитика

здесь больше нет…

3372 / 1670 / 184

Регистрация: 03.02.2010

Сообщений: 1,219

23.07.2012, 15:21

2

Visual Basic
1
Dir(path, vbDirectory) = ""



2



1702 / 189 / 19

Регистрация: 20.11.2011

Сообщений: 281

23.07.2012, 16:02

3

А зачем Вам удалять, потом создавать? Если папка не пуста, ее надо очистить. Иначе до лампочки Ваш RmDir. А в очищенной папке и MkDir не нужен:-)



1



Catstail

Модератор

Эксперт функциональных языков программированияЭксперт Python

34706 / 19227 / 4039

Регистрация: 12.02.2012

Сообщений: 32,183

Записей в блоге: 13

23.07.2012, 19:04

4

Лучший ответ Сообщение было отмечено как решение

Решение

Удалить папку не так-то просто… RmDir удаляет пустые папки. Чтобы удалить непустую папку, нужно сначала удалить ее содержимое. А в содержимом, в свою очередь, могут быть подпапки. Короче — придется обойти и вычистить все подпапки текущей папки.

Другой вариант — использовать FSO:

Visual Basic
1
2
3
Set myFSO=CreateObject("Scripting.FileSystemObject")
Set Fld=myFSO.GetFolder(CurDir & "Fold")
Fld.Delete

папка уничтожится со всем содержимым.



5



Dragokas

Эксперт WindowsАвтор FAQ

17992 / 7618 / 890

Регистрация: 25.12.2011

Сообщений: 11,351

Записей в блоге: 17

24.07.2012, 01:46

5

Еще вариант:

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
Sub ReCreate_Dir()
Dim ret&, sPath$
sPath = "e:2 а"
If FolderExists(sPath) Then
  ret = CreateObject("WScript.Shell").Run("cmd /c rd /s /q """ & sPath & """", 0, True)
End If
If Not FolderExists(sPath) Then MkDir sPath
End Sub
 
Public Function FolderExists(ByVal strPathName As String) As Boolean
On Error Resume Next
FolderExists = GetAttr(strPathName) And vbDirectory
End Function

‘какой-то ret неадыкватный: заюзал два раза функцию, чтоб наверняка. Наверно по тому что код возврата идет через CMD, а не RmDir напрямую (когда удаляет все в папке, кроме заблокированных возвращает ret=0).



3



bodeaux

3 / 3 / 0

Регистрация: 20.07.2012

Сообщений: 27

24.07.2012, 08:21

 [ТС]

6

вставил вместо RmDir(path) этот код:

Цитата
Сообщение от Catstail
Посмотреть сообщение

Visual Basic
1
2
3
Set myFSO = CreateObject("Scripting.FileSystemObject")
Set Fld = myFSO.GetFolder(path)
Fld.Delete

ситуация не изменилась — Path access error в точке MkDir (path)

Добавлено через 5 минут
Всем спасибо.

Рабочий код получился такой

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Sub createDir()
 
  Dim path As String
  path = CurDir + "Fold"
  
  Set fs = CreateObject("Scripting.FileSystemObject")
  
  If fs.folderexists(path) Then
         Call fs.DeleteFolder(path)
  End If
 
  MkDir (path)
  
End Sub



1



Эксперт WindowsАвтор FAQ

17992 / 7618 / 890

Регистрация: 25.12.2011

Сообщений: 11,351

Записей в блоге: 17

24.07.2012, 11:02

7

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



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

24.07.2012, 11:02

7

Понравилась статья? Поделить с друзьями:
  • Vba excel удалить папку с файлами
  • Vba excel фильтрация массива
  • Vba excel умный поиск
  • Vba excel фильтр содержит
  • Vba excel удалить отфильтрованные строки