Excel vba проверить существование папки

 

Антон91

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

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

#1

27.01.2020 01:11:11

Коллеги, прошу помощи, не могу разобраться в чем проблема, гугл конкретики не внес.
Как в операторе if указать условие «если папки не существует»?  Должно получиться как то примерно так

Код
dim monts as string
Sub test ()
monts = Range("A1")
IF Dir ("C:UsersivanpDesktopTeamplate AVR" & months & "") <> 0 then
MkDir ("C:UsersivanpDesktopTeamplate AVR" & months & "")
esle
kill ("C:UsersivanpDesktopTeamplate AVR" & months & ".xlsx")
end sub

Но данная строка соответственно не работает. Подскажите пожалуйста как правильно это записать.

 

vikttur

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

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

#2

27.01.2020 01:26:27

Код
...........
    monts = Range("A1").Value
    sFldr = "C:UsersivanpDesktopTeamplate AVR" & months & ""
    If Dir(sFldr, vbDirectory) = "" Then
          MkDir sFldr
    Else
...........
 

Антон91

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

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

#3

27.01.2020 01:38:21

Благодарю Вас за ответ, если вас не затруднит, просветите пещерного человека как это работает…
Это некая переменная? Что делает эта строчка?

Код
sFldr = "C:UsersivanpDesktopTeamplate AVR" & months & ""
 

vikttur

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

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

В переменную записываем полный путь к проверяемой папке

P.S.
Вначале не обратил внимания… Зачем в последней строке к имени папки дописываете расширение?

 

Ігор Гончаренко

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

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

#5

27.01.2020 01:43:50

название темы:

проверить наличие папки, если нет — создать ее, если есть — удалить одноименный xlsx-файл

Код
Sub test()
  Dim f$
  f = "C:UsersivanpDesktopTeamplate AVR" & Range("A1")
  If Dir(f, vbDirectory) = "" Then
    MkDir f
  esle
    If Dir(f & ".xlsx") <> "" Then Kill f & ".xlsx"
  End If
End Sub

Изменено: Ігор Гончаренко27.01.2020 01:46:32

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

Антон91

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

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

#6

27.01.2020 12:00:57

Цитата
vikttur написал: If Dir(sFldr, vbDirectory) = «» Then  MkDir sFldr

Я так понимаю что данная строчка удаляет все файлы с данным расширением внутри папки…

Ігор Гончаренко, благодарю вас!

 

Андрей_26

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

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

#7

27.01.2020 12:19:01

Цитата
Антон91 написал: Я так понимаю что данная строчка удаляет…

Неправильно понимаете. Данная строка проверяет наличие папки и если ее нет — то (MkDir) создает такую папку.

 

GoodPaul

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

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

А как написать конструкцию в цикле такого вида:
Если папка существует (путь к паке) Then продолжить выполнение макроса, else перейти к следующему шагу цикла?

 

Андрей VG

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

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

Excel 2016, 365

#9

01.02.2020 13:20:47

Доброе время суток

Цитата
GoodPaul написал:
продолжить выполнение макроса,

какого макроса?

Цитата
GoodPaul написал:
перейти к следующему шагу цикла?

а где собственно цикл?

 

про оператор If слышали? используйте, он справится

Изменено: Ігор Гончаренко01.02.2020 13:26:59

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

GoodPaul

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

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

Прошу прощения, имею скромное представление о VBA
Попробую описать на примере, который был выше

Sub test()
 Dim f$, i
for i = 1 to 100
 f = «C:UsersivanpDesktopTeamplate AVR» & Cells(i,1)
 If Dir(f, vbDirectory) = «» Then ‘эта строчка, если правильно понимаю, читается как если папка НЕ существует, то
   «переходим к следующему шагу цикла»
 esle
   «продолжаем выполнять макрос, который открывает файл из этой папки»
 End If
next
End Sub

Изменено: GoodPaul01.02.2020 14:22:52

 

Hugo

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

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

Что-то я не улавливаю логику… Если папка существует то проходим мимо, а если папки нет — то открываем из неё файл?
Вообще в Винде есть АПИ, а там есть такая удобная штука как MakeSureDirectoryPathExists, это если нужно гарантированно иметь папку.
А если в названиях важна диакритика — то тоже есть компонент, но его нужно поискать… нашёл: SHCreateDirectoryEx

Изменено: Hugo01.02.2020 14:12:14

 

GoodPaul

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

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

если вот эта конструкция значит, что папка НЕ существует If Dir(f, vbDirectory) = «», то все логично. Или неправильно понимаю ее и она означает, что папка существует?  

 

vikttur

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

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

В комментарии Вы написали «существует»,  это и ввело в заблуждение

Вы уже написали цикл.  И условие вписано…  В чем вопрос?

 

GoodPaul

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

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

извиняюсь, не доглядел по поводу НЕ существует)

Как прописать на VBA вот эти две строчки:
«переходим к следующему шагу цикла»
«продолжаем выполнять макрос»

 

Hugo

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

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

#16

01.02.2020 16:11:19

Цитата
GoodPaul написал:
«переходим к следующему шагу цикла»

— вот конкретно такого нет.
Но если перевернуть код из №11 так — если условие не выполняется то работаем, то и будет так как Вы хотите.

 

vikttur

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

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

#17

01.02.2020 16:32:42

Цитата
GoodPaul написал: переходим к следующему шагу цикла

Для этого ничего не нужно писать.

Код
For i = 1 To 100
' что-то делаем
Next i

For i = 1 To 100
    If 1=0 Then  
        ' что-то делаем
    End If
Next i

И первый, и второй цикл 100 раз переходит к следующему шагу

Return to VBA Code Examples

VBA allows you to check if a file or folder exists by using the Dir function.

Using the Dir Command to Check If a File Exists

As we mentioned in the introduction, the Dir function allows us to check if a selected file exists on the computer. Here is the code:

Sub CheckFileExists ()

Dim strFileName As String
Dim strFileExists As String

    strFileName = "C:UsersNikolaDesktopVBA articlesTest File Exists.xlsx"
    strFileExists = Dir(strFileName)

   If strFileExists = "" Then
        MsgBox "The selected file doesn't exist"
    Else
        MsgBox "The selected file exists"
    End If

End Sub

We first assigned the file path to the variable strFileName. Then we use the Dir function to get the file name into the variable strFileExists. If the file exists in the directory, its name will be assigned to the string variable strFileExists.  If it does not exist then strFileExists will remain blank.  Finally, the message box appears informing us if the file exists or not.

Using the Dir Command to Check If a Folder Exists

Similarly to checking if a file exists, you can check if a folder exists. You just need to add one argument to the Dir command. Let’s look at the code:

Sub CheckFolderExists ()

Dim strFolderName As String
Dim strFolderExists As String

    strFolderName = "C:UsersNikolaDesktopVBA articlesTest Folder"
    strFolderExists = Dir(strFolderName, vbDirectory)

    If strFolderExists = "" Then
        MsgBox "The selected folder doesn't exist"
    Else
        MsgBox "The selected folder exists"
    End If

End Sub

We first assigned the folder path to the variable strFolderName. Then we use the Dir function to get the file name into the variable strFileExists. In order to check a folder, we need to add the second argument to the function – vbDirecotry. If the folder exists in the directory, its name will be assigned to the variable strFolderExists. If not strFolderExists will remain blank.

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!

I have a spreadsheet that upon clicking a button will duplicate itself by copying/pasting everything to a new workbook and save the file with a name that is dependent upon some variable values (taken from cells on the spreadsheet).
My current goal is to get it to save the sheet in different folders depending on the name of client name (cell value held in variable), while this works on the first run, I get an error after.

The code checks if the directory exists and creates it if not.
This works, but after it is created, running it a second time throws the error:

Runtime Error 75 — path/file access error.

My code:

Sub Pastefile()

Dim client As String
Dim site As String
Dim screeningdate As Date
screeningdate = Range("b7").Value
Dim screeningdate_text As String
screeningdate_text = Format$(screeningdate, "yyyy-mm-dd")
client = Range("B3").Value
site = Range("B23").Value

Dim SrceFile
Dim DestFile

If Dir("C:2013 Recieved Schedules" & "" & client) = Empty Then
    MkDir "C:2013 Recieved Schedules" & "" & client
End If

SrceFile = "C:2013 Recieved Schedulesschedule template.xlsx"
DestFile = "C:2013 Recieved Schedules" & client & "" & client & " " & site & " " & screeningdate_text & ".xlsx"

FileCopy SrceFile, DestFile

Range("A1:I37").Select
Selection.Copy
Workbooks.Open Filename:= _
    "C:2013 Recieved Schedules" & client & "" & client & " " & site & " " & screeningdate_text & ".xlsx", UpdateLinks:= _
    0
Range("A1:I37").PasteSpecial Paste:=xlPasteValues
Range("C6").Select
Application.CutCopyMode = False
ActiveWorkbook.Save
ActiveWindow.Close

End Sub

You’ll have to excuse my lack of knowledge in this area, I am still learning.
I have a very strong feeling it has something to do with the directory checking logic, as when the error is thrown the MkDir line is highlighted.

 Как проверить, существует ли папка, и не создать ли ее?

Вы когда-нибудь пытались проверить, существует ли папка на листе Excel? В этой статье я расскажу о том, как проверить, существует ли папка по указанному пути, в противном случае папка будет создана автоматически по указанному пути.

Проверьте, существует ли папка в определенном пути к файлу с кодом VBA

Создайте папку, если она не существует в определенном пути к файлу с кодом VBA


стрелка синий правый пузырь Проверьте, существует ли папка в определенном пути к файлу с кодом VBA

Следующий код VBA может помочь вам проверить, существует ли папка по определенному пути к файлу, сделайте следующее:

1. Удерживайте ALT + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. Нажмите Вставить > Модулии вставьте следующий код в Модули Окно.

Код VBA: проверьте, существует ли папка в определенном пути к файлу:

Sub Test_Folder_Exist_With_Dir()
'Updateby Extendoffice
    Dim sFolderPath As String
    sFolderPath = "C:UsersDT168DesktopTest folder"
    If Right(sFolderPath, 1) <> "" Then
        sFolderPath = sFolderPath & ""
    End If
    If Dir(sFolderPath, vbDirectory) <> vbNullString Then
        MsgBox "Folder exist", vbInformation, "Kutools for Excel"
    Else
        MsgBox "Folder doesn't exist", vbInformation, "Kutools for Excel"
    End If
End Sub

Примечание: В приведенном выше коде вы должны изменить путь и имя папки C: Users DT168 Desktop Test папка к вашему необходимому.

3, Затем нажмите F5 ключ для запуска этого кода, вы получите следующие результаты:

папка doc существует 1


стрелка синий правый пузырь Создайте папку, если она не существует в определенном пути к файлу с кодом VBA

Проверьте, существует ли папка в пути к файлу, если нет, чтобы создать ее по этому конкретному пути к файлу, следующий код VBA может помочь вам завершить эту работу.

1. Удерживайте ALT + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.

2. Нажмите Вставить > Модулии вставьте следующий код в Модули Окно.

Код VBA: создайте папку, если она не существует в пути к файлу:

Sub MakeMyFolder()
'Updateby Extendoffice
    Dim fdObj As Object
    Application.ScreenUpdating = False
    Set fdObj = CreateObject("Scripting.FileSystemObject")
    If fdObj.FolderExists("C:UsersDT168DesktopTest folder") Then
        MsgBox "Found it.", vbInformation, "Kutools for Excel"
    Else
        fdObj.CreateFolder ("C:UsersDT168DesktopTest folder")
        MsgBox "It has been created.", vbInformation, "Kutools for Excel"
    End If
    Application.ScreenUpdating = True
End Sub

Внимание: В приведенном выше коде вы должны изменить путь и имя папки C: Users DT168 Desktop Test папка к вашему необходимому.

3. После вставки кода нажмите F5 ключ для его запуска:

(1.) Если папка существует, появится диалоговое окно, как показано на следующем снимке экрана:

папка doc существует 2

(2.) Если папка не существует, она будет создана сразу по определенному пути, и появится окно подсказки, напоминающее вам, что папка была создана, см. Снимок экрана:

папка doc существует 3


Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

The function that allows us to check if a file or folder exists is know as the DIR function.  The syntax for the DIR function is as follows:

DIR [( path [, attributes ])]

The PATH argument is basically an address which returns the name of your file or folder.  If the name is not found, DIR returns an empty string.

The ATTRIBUTES argument (which are optional) are listed in the below table.

ConstantVALUE Value Description
vbNormal 0 (Default) Files with no attributes
vbReadOnly 1 Read-only files
vbHidden 2 Hidden files
vbSystem 4 System files
vbDirectory 16 Directories or folders

The default is vbNormal, which are files with no specific attributes.  You can filter for files with a specific attribute by using the constants listed above.

An interesting thing you can use with the DIR function are wildcards.  Wildcards represent “any characters” and are useful when you want to capture multiple items in a search based on a pattern of characters.  There are two wildcard characters:

Asterisk (*) – This wildcard character will allow for any character(s) in any quantity.

Examples:  

Exc* (any text starting with “Exc”)

*el (any text ending with “el”)

Exc*el (any text starting with “Exc”, ending with “el”, and any character in between)

Question Mark (?) – This wildcards character will allow for any character in a single character position

Examples:   

??cel (The first and second characters can be anything, but the third through fifth characters must be “cel”)

Ex?el (The first and second characters must be “Ex”, the fourth and fifth characters must be “el”, but the third character can be anything)

Practical Examples

Task #1

We will use the DIR function to check if a file exists.  If the file doesn’t exist, we will display a “File does not exist” message to the user.  If the file exists, we will open the file.

Task #2

We will use the DIR function to check if a folder exists.  If the folder doesn’t exist, we will prompt the user to ask if they would like to create that folder.  If the responds with a “Yes”, we will create the folder for them.

Task #1 (Version 1) – Checking for the existence of a file

First, open the Visual Basic Editor (ALT-F11) and create an empty module (i.e. “LessonsFilesFolders”).

The DIR function returns a string, so we need to declare a variable named FileName to hold the returned value.

Dim FileName As String

The next step is to query a folder for a file and return the filename if it exists, or an empty string if the file does not exist.  We will store the response in the FileName variable we created in the previous step.

FileName = VBA.FileSystem.Dir(“your folder nameyour file name”)

In our example we will use the following code:

FileName = VBA.FileSystem.Dir(“C:UsersLGDesktopVBAS2_recordMacros_start.xlsx”)

If the file does not exist, the DIR function will return an empty string.  We will test for the empty string response with an IF statement.  If the file does not exist, we will display a message stating such.  If the file does exist, this first version will simply show the filename in a message box.

If FileName = VBA.Constants.vbNullString Then
    MsgBox "File does not exist."
Else
    MsgBox FileName
End If

The completed code should look like the following:

Sub FileExists()
Dim FileName As String
    FileName = VBA.FileSystem.Dir("C:UsersLGDesktopVBAS2_recordMacros_start.xlsx")
    If FileName = VBA.Constants.vbNullString Then
        MsgBox "File does not exist."
    Else
        MsgBox FileName
    End If
    
End Sub

Execute the code by pressing F5 and observe the response.

This confirms that the file exists in the defined folder.

Task #1 (Version 2) – Checking for the existence of a file using wildcards

Alter the code to use wildcards when searching for the filename.

FileName = VBA.FileSystem.Dir("C:UsersLGDesktopVBAS2_*start.xls?)

We will also alter the code; instead of displaying a message, we will open the requested file.

Workbooks.Open "C:UsersLGDesktopVBA" & FileName

The updated code should appear as follows:

Sub FileExists()
Dim FileName As String
    FileName = VBA.FileSystem.Dir("C:UsersLGDesktopVBAS2_*start.xls?")
    If FileName = VBA.Constants.vbNullString Then
        MsgBox "File does not exist."
    Else
        Workbooks.Open "C:UsersLGDesktopVBA" & FileName
    End If
    
End Sub

Execute the code by pressing F5 and observe that the file opens.

Task #2 – Check if a folder exists

In this task, we will check to see if a folder exists.  If the folder does not exist, we will prompt the user and ask if they would like to create the folder.

We will create two variables:

Path – Hold the full folderfilename information

Folder – Hold only the folder name

Dim Path as String
Dim Folder as String

We will set the Path variable to point to a folder that does not exist:

Path = “C:UsersLGDesktopVBAS12”

We will set the Folder variable to hold the folder location stored by the Path variable.  Because this is a folder, we will use the optional constant vbDirectory in the DIR function.

Folder = Dir(Path,vbDirectory)

As we did earlier, we will check to see if the response returns an empty string.  If the Folder variable contains an empty string, we will prompt the user to ask if they wish to create the folder.

We need to store the user’s response, so we will create a variable to hold the response.

Dim Answer as VbMsgBoxResult

If the folder does not exist, we will display a message and store the user’s response in the Answer variable.

Answer = MsgBox("Path does not exist. Would you like to create it?", vbYesNo, "Create Path?")

Now we will test the answer.  We will use a Case statement to test the response.

If the user responds with “Yes”, we will create the folder.  If the user responds with anything else, we will exit the subroutine.

Select Case Answer
    Case vbYes
        VBA.FileSystem.MkDir (Path)
    Case Else
        Exit Sub
End Select

If the folder does exist, we will inform the user of its existence with a message box response.

Else
    MsgBox "Folder exists."

The completed code should look like the following:

Sub Path_Exists()
Dim Path As String
Dim Folder As String
Dim Answer As VbMsgBoxResult
    Path = "C:UsersLGDesktopVBAS12"
    Folder = Dir(Path, vbDirectory)
 
    If Folder = vbNullString Then
        Answer = MsgBox("Path does not exist. Would you like to create it?", vbYesNo, "Create Path?")
        Select Case Answer
            Case vbYes
                VBA.FileSystem.MkDir (Path)
            Case Else
                Exit Sub
        End Select
    Else
        MsgBox "Folder exists."
    End If
End Sub

Execute the code by pressing F5.  Because the folder does not exist, we are presented with the following message prompt.

If we answer “Yes”, the folder is created.

If we execute the macro a second time, we see the following response.

This is because the folder was created in the previous test.

Conclusion

We have demonstrated how you can use the DIR function to test whether a file or folder exists and decide what actions you wish to perform depending on the outcome of the test.

Practice Workbook

Feel free to Download the Workbook HERE.

Excel Download Practice file

Published on: November 22, 2018

Last modified: February 20, 2023

Microsoft Most Valuable Professional

Leila Gharani

I’m a 5x Microsoft MVP with over 15 years of experience implementing and professionals on Management Information Systems of different sizes and nature.

My background is Masters in Economics, Economist, Consultant, Oracle HFM Accounting Systems Expert, SAP BW Project Manager. My passion is teaching, experimenting and sharing. I am also addicted to learning and enjoy taking online courses on a variety of topics.

Понравилась статья? Поделить с друзьями:
  • Excel vba присвоить ячейке формулу
  • Excel vba присвоить значение массиву
  • Excel vba присвоить диапазон
  • Excel vba пример массива
  • Excel vba при редактировании ячейки