Excel vba if not dir

VBA Check If Folder Exists If Not Create It in specified name using VBA in Excel. We are using 2 methods to check folder exists or not. Those are Dir VBA function and FileSystemObject object. In the following tutorial let us see an example macro code. And also see the step by step instructions to run vba code in the visual basic editor(VBE) window.

Table of Contents:

  • Objective
  • Example to Check If Folder Exists If Not Create It using VBA Dir Function
  • VBA Checking If Folder Exists If Not Create It using FileSystemObject(FSO) Object
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

Example to Check If Folder Exists If Not Create It using VBA Dir Function

Let us see an example macro to check specified folder exists or not. If it is not available create a new folder using VBA Dir function to check folder exists or not. First we are checking specified folder is available or not. If it exists, then displays message on the screen. If doesn’t exists, creating new folder using VBA MkDir function. After successfully creating folder displaying message on the screen for user notification.

'VBA Checking If Folder Exists If Not Create It using Dir Function
Sub VBAF1_Checking_If_Folder_Exists_If_Not_Create_It_Using_Dir_Function()
    
     'Variable declaration
    Dim sFolderPath As String
    Dim oFSO As Object
    
    'Define Folder Path
    sFolderPath = "C:VBAF1Files and Folders"
        
    'Check Specified Folder exists or not
    If Dir(sFolderPath) <> "" Then
        'If file is available
        MsgBox "Folder already exists!", vbInformation, "VBAF1"
        Exit Sub
    End If
         
    'If folder is not available
    MkDir sFolderPath
    
    'Display Message
    MsgBox "New folder has created successfully!", vbInformation, "VBAF1"
    
End Sub

Output: You can find following output screenshot for your reference. You can see different outputs in the screen shot. If folder available it displays first message. 2nd message displays when folder is created newly.
VBA Check If Folder Exists If Not Create It

VBA Checking If Folder Exists If Not Create It using FileSystemObject(FSO) Object

Let us another example macro to check specified Folder exists or not. If it is not available create a new Folder using VBA FileSystemObject(FSO) object to check Folder exists or not. In the below example VBA MkDir function helping us to create new folder.

'VBA Checking If Folder Exists If Not Create It using FSO Object
Sub VBAF1_Check_If_Folder_Exists_If_Not_Create_It_Using_FSO_Object()
    
    'Variable declaration
    Dim sFolderPath As String
    Dim oFSO As Object
    
    'Define Folder Path
    sFolderPath = "C:VBAF1Files and Folders2"
    
    'Create FSO Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    
    'Check Specified Folder exists or not
    If oFSO.FolderExists(sFolderPath) Then
        'If Folder is available
        MsgBox "Folder already exists!", vbInformation, "VBAF1"
        Exit Sub
    End If
    
    'If folder is not available
    MkDir sFolderPath
    
    'Display Message
    MsgBox "New folder has created successfully!", vbInformation, "VBAF1"
    
End Sub

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

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.

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!

7 ответов

что-то вроде этого

лучше использовать переменную рабочей книги для обеспечения дальнейшего контроля (при необходимости) открытой рабочей книги

обновлено, чтобы проверить, что имя файла является реальной рабочей книгой, — которая также делает избыточную первоначальную проверку, отличную от сообщения пользователя, чем текстовое поле пустым

Dim strFile As String
Dim WB As Workbook
strFile = Trim(TextBox1.Value)
Dim DirFile As String
If Len(strFile) = 0 Then Exit Sub

DirFile = "C:Documents and SettingsAdministratorDesktop" & strFile
If Len(Dir(DirFile)) = 0 Then
  MsgBox "File does not exist"
Else
 On Error Resume Next
 Set WB = Workbooks.Open(DirFile)
 On Error GoTo 0
 If WB Is Nothing Then MsgBox DirFile & " is invalid", vbCritical
End If

brettdj
03 май 2013, в 06:15

Поделиться

Я использую эту функцию для проверки существования файла:

Function IsFile(ByVal fName As String) As Boolean
'Returns TRUE if the provided name points to an existing file.
'Returns FALSE if not existing, or if it a folder
    On Error Resume Next
    IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory)
End Function

Patrick Honorez
30 янв. 2015, в 14:37

Поделиться

Для проверки существования можно также использовать (работает как для файлов, так и для файлов):

Not Dir(DirFile, vbDirectory) = vbNullString

Результатом является True если файл или каталог существует.

Пример:

If Not Dir("C:Temptest.xlsx", vbDirectory) = vbNullString Then
    MsgBox "exists"
Else
    MsgBox "does not exist"
End If

ZygD
18 нояб. 2015, в 06:21

Поделиться

Вот мой обновленный код. Проверяет, существует ли версия до сохранения и сохраняет в качестве следующего доступного номера версии.

Sub SaveNewVersion()
    Dim fileName As String, index As Long, ext As String
    arr = Split(ActiveWorkbook.Name, ".")
    ext = arr(UBound(arr))

    fileName = ActiveWorkbook.FullName

    If InStr(ActiveWorkbook.Name, "_v") = 0 Then
        fileName = ActiveWorkbook.Path & "" & Left(ActiveWorkbook.Name, InStr(ActiveWorkbook.Name, ".") - 1) & "_v1." & ext
    End If

   Do Until Len(Dir(fileName)) = 0

        index = CInt(Split(Right(fileName, Len(fileName) - InStr(fileName, "_v") - 1), ".")(0))
        index = index + 1
        fileName = Left(fileName, InStr(fileName, "_v") - 1) & "_v" & index & "." & ext

    'Debug.Print fileName
   Loop

    ActiveWorkbook.SaveAs (fileName)
End Sub

Andrew Prostko
21 март 2018, в 21:18

Поделиться

Я брошу это там, а потом утку. Обычная причина, чтобы проверить, существует ли файл, — это избежать ошибки при попытке ее открыть. Как насчет использования обработчика ошибок, чтобы справиться с этим:

Function openFileTest(filePathName As String, ByRef wkBook As Workbook, _
                      errorHandlingMethod As Long) As Boolean
'Returns True if filePathName is successfully opened,
'        False otherwise.
   Dim errorNum As Long

'***************************************************************************
'  Open the file or determine that it doesn't exist.
   On Error Resume Next:
   Set wkBook = Workbooks.Open(fileName:=filePathName)
   If Err.Number <> 0 Then
      errorNum = Err.Number
      'Error while attempting to open the file. Maybe it doesn't exist?
      If Err.Number = 1004 Then
'***************************************************************************
      'File doesn't exist.
         'Better clear the error and point to the error handler before moving on.
         Err.Clear
         On Error GoTo OPENFILETEST_FAIL:
         '[Clever code here to cope with non-existant file]
         '...
         'If the problem could not be resolved, invoke the error handler.
         Err.Raise errorNum
      Else
         'No idea what the error is, but it not due to a non-existant file
         'Invoke the error handler.
         Err.Clear
         On Error GoTo OPENFILETEST_FAIL:
         Err.Raise errorNum
      End If
   End If

   'Either the file was successfully opened or the problem was resolved.
   openFileTest = True
   Exit Function

OPENFILETEST_FAIL:
   errorNum = Err.Number
   'Presumabley the problem is not a non-existant file, so it's
   'some other error. Not sure what this would be, so...
   If errorHandlingMethod < 2 Then
      'The easy out is to clear the error, reset to the default error handler,
      'and raise the error number again.
      'This will immediately cause the code to terminate with VBA standard
      'run time error Message box:
      errorNum = Err.Number
      Err.Clear
      On Error GoTo 0
      Err.Raise errorNum
      Exit Function

   ElseIf errorHandlingMethod = 2 Then
      'Easier debugging, generate a more informative message box, then terminate:
      MsgBox "" _
           & "Error while opening workbook." _
           & "PathName: " & filePathName & vbCrLf _
           & "Error " & errorNum & ": " & Err.Description & vbCrLf _
           , vbExclamation _
           , "Failure in function OpenFile(), IO Module"
      End

   Else
      'The calling function is ok with a false result. That is the point
      'of returning a boolean, after all.
      openFileTest = False
      Exit Function
   End If

End Function 'openFileTest()

riderBill
10 дек. 2015, в 06:57

Поделиться

Возможно, это вызвано переменной Filename

File = TextBox1.Value

Должен быть

Filename = TextBox1.Value

matzone
03 май 2013, в 04:48

Поделиться

Вы должны установить цикл условий, чтобы проверить значение TextBox1.

If TextBox1.value = "" then
   MsgBox "The file not exist" 
   Exit sub 'exit the macro
End If

Надеюсь, это поможет вам.

Leng Keong
03 май 2013, в 04:48

Поделиться

Ещё вопросы

  • 1org.hibernate.exception.JDBCConnectionException: не удается открыть соединение
  • 0версии c ++ и g ++ одинаковые или разные
  • 1Как установить PreferenceScreen в другой макет в Android
  • 1Экземпляр приложения .Net завершается через 13 минут, 20 секунд, независимо от того, находится ли пользователь в режиме ожидания или нет
  • 1Заменить несколько вхождений одного и того же символа между двумя другими персонажами
  • 1priority-web-sdk: реализация поля выбора
  • 0Область видимости переменной PHP после нескольких включений
  • 1Как использовать java.util.Date в качестве ключа карты в Groovy
  • 0В разрешении на сессию отказано Laravel Forge и OAuth
  • 1Невозможно войти с помощью паспорта — Nodejs
  • 1я не понимаю, что такое «защищенная пустота Page_Load»
  • 0jQuery гармошка и мышка на навигацию по вертикальному меню
  • 0Android 2.2 / 2.3 веб-просмотр делает невидимым
  • 1Javascript заполнить массив оператором IF
  • 0нг-если вызывается до того, как данные будут готовы с AngularJS
  • 1Класс закрытых символов (регулярное выражение)
  • 0JQuery UI DataPicker с readonly в Angular
  • 1нарисовать несколько линий поверх диаграммы Ганта d3.js
  • 1Пользовательский Razor ForEach View
  • 0Распределение элементов данных без указателя в C ++ в экземпляре класса указателя в куче или в стеке
  • 0Не могу получить значение из глобальной переменной
  • 0перезаписать файл .txt после того, как пользователь отредактирует его C ++
  • 1javascript копия с execCommand
  • 0Ошибка загрузки CI. Вы не выбрали файл для загрузки
  • 0Отправка файла CSV hude напрямую в вывод браузера не работает
  • 0Jquery не работает на PhoneGap 3.0
  • 1Как добавить точку останова в блокноте Jupyter?
  • 1Как запретить пользователю вводить специальные символы в текстовое поле SWT
  • 0Определить уникальные атрибуты данных
  • 1Активизировать вид с помощью движущегося пальца
  • 1Ionic3 фоновое изображение из переменной
  • 1Как я могу узнать, находится ли пользователь на определенном сайте?
  • 1Аутентификация на диске Google показывает ошибку «idpiframe_initialization_failed»
  • 0Проверка только в одном месте — в классах типа формы
  • 0Как использовать в «этом» первом сборнике с уроком?
  • 0HTML / CSS: несколько последовательных полноэкранных изображений
  • 0вызов функции javascript внутри функции php
  • 1Пользовательский курсор в реальном времени MonoGame
  • 1Обновить родительский класс в Vue.js
  • 1Определите новый сервер, выбрав GlassFish 3.1. Внутренняя ошибка — Eclipse Luna
  • 1Объединяйте строки, используя C # Linq
  • 1python3 — обновленное значение глобальной переменной не используется, вместо него используется старое значение
  • 0Проблема с вычислением значений для вложенного цикла
  • 0не удается скачать или открыть пустой PDF-файл PHP
  • 1Обслуживание приложения останавливается, когда телефон не заряжается
  • 1Python: нажмите на следующую страницу без ссылки, чтобы следовать (javascript / AJAX)
  • 4Какая альтернатива для «toNotEqual» в жасмине?
  • 0Таблица уже существует sql
  • 0Javascript на клике не показывает элементы, которые он должен

 

Антон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 раз переходит к следующему шагу

  • #2

Say the directory is c:local

Code:

if Dir("c:local",vbDirectory) ="" then
  'directory doesn't exist
else
  'directory does exist
end if

  • #3

Here are two approches:

Code:

Sub MakeMyFolder()
Dim fsoFSO
Set fsoFSO = CreateObject("Scripting.FileSystemObject")
If fsoFSO.FolderExists("C:_DevelopmentDeleteme") Then
    MsgBox "found it"
Else
    fsoFSO.CreateFolder ("C:_DevelopmentDeleteme")
    MsgBox "Done"
End If
End Sub

or….

Code:

Sub MakeMyFolder()
If Dir("C:_DevelopmentDeleteme", vbDirectory) = "" Then
    MkDir Path:="C:_DevelopmentDeleteme"
    MsgBox "Done"
Else
    MsgBox "found it"
End If
End Sub

Is that something you can work with?

  • #4

Beautiful! Works like a charm. Tested with and without numerous times.

Thank you!

Today’s Office automation tutorial is focused on learning how to verify that a file exists in one of your computer directories.

Preparation

If you are somewhat new to coding, ensure that the Microsoft Office Excel development tab is enabled and that you are familiar with some basic Excel VBA.

Checking if a file exists with Excel VBA

The following code leverages input boxes in order to capture the path to the file as well as the file name itself from the user.

Then it leverages the Dir method to verify if the file path indeed exists.

Lastly, it displays a message box to the user with the check result.

Sub Check_file_exists()

Dim NameDir As String
Dim NameFile As String

'Capture the file path and name from the users
NameDir = InputBox("Enter file directory")
NameFile = InputBox("Enter file name")

'Check whether the file exists
If (Dir(NameDir & NameFile)) = "" Then
    MsgBox ("File doesn't exist")

    Else
    
    MsgBox ("File exists")
    End If
End Sub

Check if a folder exists

In quite a similar fashion you can check whether a specific folder exists in your operating system. Also here we leverage the Dir method, but with the vbDirectory parameter.

Sub Check_folder_exists()

Dim NameDir As String

NameDir = InputBox("Enter file directory")


If (Dir(NameDir, vbDirectory)) = "" Then
    MsgBox ("Folder doesn't exist")

    Else
    
    MsgBox ("Folder exists")
    End If
End Sub

Using the Code

  • Open Microsoft Excel and navigate to your workbook.
  • Hit Developer and then hit Visual Basic.
  • Copy and Paste the code from above as a subroutine in either a specific sheet of your VBA module.
  • Run (F5) the code.
  • Save your workbook.

Possible extensions

The boiler plate code above an be extended for the following use cases:

  • Create a folder / file if it doesn’t already exist.
  • Delete a file of folder provided they are present in your operating system file directory.
  • Search for files/folders using a wildcard.

Понравилась статья? Поделить с друзьями:
  • Excel vba if not boolean
  • Excel vba if listbox not selected
  • Excel vba if is not integer
  • Excel vba if in between
  • Excel vba if iif