Vba excel проверить есть ли файл

Вы можете использовать функцию Dir с параметром vbHidden

Visual Basic
1
2
3
4
5
6
Sub test1()
   Dim fileN As String
 
   fileN = "D:KWReestrIterPara.txt"
   If Dir(fileN, vbHidden) <> "" Then MsgBox fileN & " существует"
End Sub

Это ДОБАВИТ выдачу скрытых файлов к обычным. То есть, если у вас есть файл IterPara.txt и на нем дополнительных атрибутов не стоит, он будет выдан. Если он скрытый — тоже выдан. А если на нем стоит, например, атрибут «системный» и не стоит «скрытый» — не будет. Ну и в случае, если такого файла нет.

Если же надо выдать сообщение тогда и только тогда, когда файл имеет атрибут «скрытый», лучше воспользоваться FSO. Тут перебор файлов в каталоге, но можно и отдельный проверять.

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
Sub test2()
   Dim oFSO As Object, oFolder As Object, oFile As Object
 
   Set oFSO = CreateObject("Scripting.FileSystemObject")
   Set oFolder = oFSO.GetFolder("D:KWReestr")
 
   For Each oFile In oFolder.Files
     If oFile.Attributes And 2 Then
         MsgBox oFile.Path & " is Hidden"
     End If
   Next
End Sub

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!

 

TSM

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

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

Может кто-то знает, как проверить существует файл или нет?  
Проблема такова, автоматом происходит подстановка картинок к строкам с названиями, маркрос ищет название определённой ячейки в выбранной строке и вставляет картинку с аналогичным названием, а что делать, если картинки такой почему-то нет? Как до начала вставки проверить есть она или нет?

Is This the World We Created?

 

Sub Макрос1()  
   If Dir(«C:Picture.jpg») = «» Then  
       MsgBox «Такой картинки нет!», 48, «Ошибка»  
   Else  
       MsgBox «Такая картинка есть!», 64, «Картинка»  
   End If  
End Sub

 

TSM

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

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

Спасибо, всё работает.  

  Но столкнулся с проблемой, если сервер, на которм лежат фотографии отключен, в этом случае идёт длительная проверка, а потом ошибка. Можно ли также проверять наличие сервера и если он не найден перенаправлять на внутренний диск компа?

Is This the World We Created?

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

Sub Check_Disk()  
If Dir(«C:*», vbSystem) <> «» Then  
MsgBox «Диск есть»  
Else: MsgBox «Диска нет»  
End If  
End Sub

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

TSM

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

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

Не работает корректно. Когда диск подключен, всё OK. Но стоит отключиться от сети и следует длительная проверка, потом выскакивает сообщение    
Run-time error ’52’:    
Bad file name or number  

  Пробовал использовать номер ошибки, но что-то видимо не так делаю. Код ниже:  

  Sub Check_Disk()  
If Dir(«\192.168.1.200c*», vbSystem) <> «» Then  
On Error Resume Next  
If Err.Number = 52 Then  
Err.Clear  
MsgBox «Диска нет»  
Exit Sub  
End If  
MsgBox «Диск есть»  
Else: MsgBox «Диска нет»  
End If  
End Sub

Is This the World We Created?

 

New

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

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

Предлагаю такой вариант  

  Sub Check_Disk()  
   On Error Resume Next  
   If Dir(«\192.168.1.200c», vbSystem) <> «» Then  
       If Err = 52 Then  
            Err.Clear  
            MsgBox «Диска нет!», 48, «Ошибка»  
            Exit Sub  
        End If  
       If Err <> 0 Then  
           MsgBox «Произошло ошибка!», 48, «Ошибка»  
           Exit Sub  
       Else  
           On Error GoTo 0  
           MsgBox «Диск есть!», 64, «»  
       End If  
   End If  
End Sub

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

Странно…У меня все работает.  
А здесь «If Dir(«\192.168.1.200c*», vbSystem) <> «» Then» после «с» не надо двоеточие ставить?  
If Dir(«\192.168.1.200c:*», vbSystem) <> «» Then

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

New

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

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

На самом деле инструкцию On Error Resume Next надо выше поднять на одну строку

 

TSM

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

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

#9

24.12.2008 19:35:11

Всё заработало! Спасибо всем за участие в решении проблемы.  
Pavel55 — отдельное спасибо.  

  it’s a kind of magic

Is This the World We Created?

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.

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

Поделиться

Ещё вопросы

  • 1Оптимизация в коде для суммы
  • 0Копировать вставить gulp node_modules
  • 1Путать с подписью Android APK?
  • 0Ошибка вывода с параллельными массивами
  • 0угловое начальное приложение изнутри
  • 1Сканирование тегов NFC только запускает мое приложение для запуска
  • 1Использование SupportMapFragment вместо MapFragment
  • 0Не удается удалить файлы cookie SMSESSION, PHPSESSID, в Siteminder
  • 1HTML Canvas и использование памяти
  • 1Ошибка при попытке использовать Angr на OS X
  • 0Sql Query, не получая правильные значения с помощью функции CURDATE ()
  • 0Загрузить JSON из загруженного файла
  • 0Слайд-шоу с изменением атрибута img src
  • 0IE думает, что float initial — это float left?
  • 0Показать выбранное значение в другом элементе DIV
  • 0PHP для JS — передача значения зацикленного элемента в JS
  • 1Выбор комбинаций переменных из строк DataFrame
  • 0Рассчитать массив уникальных стеблей в JavaScript?
  • 1Как отправить XML-файл, используя http пост в Android. Где я положил XML-файлы в коде
  • 1AsyncTask: ClassCastException: java.lang.Object [] не может быть приведен к java.lang.String []
  • 1Как я могу рассчитать текущее расстояние до точек полилинии на Google Maps v2 в Android?
  • 0Установить фокус после определенного элемента в поле ввода в jquery / javascript
  • 1NullPointerException пользовательский адаптер просмотра списка
  • 1Как сгруппировать по столбцу в pandas и применить ifelse на основе значений столбца
  • 0Использование ui-роутера и параметров
  • 1R эквивалент Python’s Dask
  • 0ионный сбор-повтор не работает
  • 0Обработчик события кнопки отправки jQuery предотвращает проверку формы для обязательных полей ввода
  • 1Загрузите несколько моделей DNN в тензор потока и используйте их несколько раз
  • 0Не удается получить значение параметра при использовании Angularjs
  • 0Как правильно минимизировать накладные расходы на соединение MySQL в многопоточном приложении Python? [Дубликат]
  • 1Разделение вложенной функции
  • 1Как прикрепить аудио файл к MMS в Android?
  • 0Как получить все продукты из одной таблицы и объединить одну строку из другой таблицы, которая содержит несколько строк?
  • 0Вертикальная укладка преобразованного текста с использованием Sass CSS и FlexBox
  • 1Android: startActivityForResult всегда имеет значение null и принудительно закрывает мое приложение
  • 0Как получить текст якоря, который находится внутри текстового узла в JQuery
  • 1Я не могу получить действие просмотра в Gmail при отправке электронной почты с использованием почтового API Java
  • 1Отметить задачу как выполненную
  • 1Разобрать ресурс в d3.queue
  • 0Ошибка JavaScript: ожидается объект
  • 0Как заказать строки DATETIME с [] в MySQL
  • 1InstallUtil какая версия фреймворка использовалась для установки сервиса?
  • 0запретить замену «& reg» на «®» в строке запроса
  • 0Закрытие клиентского сокета, после того как сервер уже закрыл свою сторону
  • 0Вставка латинских символов в mysql с использованием php?
  • 1Подписать Xml цифровым сертификатом в формате PKCS # 7 в DER (Рек. МСЭ-Т X.690)
  • 0Получить счет из двух разных таблиц на основе datetime в MySQL
  • 0Добавленный DIV отображается только при изменении размера
  • 0Получить всю зарплату сотрудника из таблиц сотрудников с 3-й по величине зарплаты в MYSQL

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