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!

Sub test()

thesentence = InputBox("Type the filename with full extension", "Raw Data File")

Range("A1").Value = thesentence

If Dir("thesentence") <> "" Then
    MsgBox "File exists."
Else
    MsgBox "File doesn't exist."
End If

End Sub

In this when i pickup the text value from the input box, it doesn’t work. If however, if remove "the sentence" from If Dir() and replace it with an actual name in the code, it works. Can somebody help?

vba_user111's user avatar

asked Jul 20, 2012 at 6:25

Dinesh Goel's user avatar

Note your code contains Dir("thesentence") which should be Dir(thesentence).

Change your code to this

Sub test()

thesentence = InputBox("Type the filename with full extension", "Raw Data File")

Range("A1").Value = thesentence

If Dir(thesentence) <> "" Then
    MsgBox "File exists."
Else
    MsgBox "File doesn't exist."
End If

End Sub

answered Jul 20, 2012 at 6:31

Cylian's user avatar

CylianCylian

10.8k4 gold badges43 silver badges55 bronze badges

4

Use the Office FileDialog object to have the user pick a file from the filesystem. Add a reference in your VB project or in the VBA editor to Microsoft Office Library and look in the help. This is much better than having people enter full paths.

Here is an example using msoFileDialogFilePicker to allow the user to choose multiple files. You could also use msoFileDialogOpen.

'Note: this is Excel VBA code
Public Sub LogReader()
    Dim Pos As Long
    Dim Dialog As Office.FileDialog
    Set Dialog = Application.FileDialog(msoFileDialogFilePicker)

    With Dialog
        .AllowMultiSelect = True
        .ButtonName = "C&onvert"
        .Filters.Clear
        .Filters.Add "Log Files", "*.log", 1
        .Title = "Convert Logs to Excel Files"
        .InitialFileName = "C:InitialPath"
        .InitialView = msoFileDialogViewList

        If .Show Then
            For Pos = 1 To .SelectedItems.Count
                LogRead .SelectedItems.Item(Pos) ' process each file
            Next
        End If
    End With
End Sub

There are lots of options, so you’ll need to see the full help files to understand all that is possible. You could start with Office 2007 FileDialog object (of course, you’ll need to find the correct help for the version you’re using).

answered Jul 20, 2012 at 7:19

ErikE's user avatar

ErikEErikE

48.4k23 gold badges150 silver badges194 bronze badges

1

Correction to fileExists from @UberNubIsTrue :

Function fileExists(s_directory As String, s_fileName As String) As Boolean

  Dim obj_fso As Object, obj_dir As Object, obj_file As Object
  Dim ret As Boolean
   Set obj_fso = CreateObject("Scripting.FileSystemObject")
   Set obj_dir = obj_fso.GetFolder(s_directory)
   ret = False
   For Each obj_file In obj_dir.Files
     If obj_fso.fileExists(s_directory & "" & s_fileName) = True Then
        ret = True
        Exit For
      End If
   Next

   Set obj_fso = Nothing
   Set obj_dir = Nothing
   fileExists = ret

 End Function

EDIT: shortened version

' Check if a file exists
Function fileExists(s_directory As String, s_fileName As String) As Boolean

    Dim obj_fso As Object

    Set obj_fso = CreateObject("Scripting.FileSystemObject")
    fileExists = obj_fso.fileExists(s_directory & "" & s_fileName)

End Function

answered May 29, 2013 at 19:14

amackay11's user avatar

amackay11amackay11

7191 gold badge10 silver badges17 bronze badges

3

just get rid of those speech marks

Sub test()

Dim thesentence As String

thesentence = InputBox("Type the filename with full extension", "Raw Data File")

Range("A1").Value = thesentence

If Dir(thesentence) <> "" Then
    MsgBox "File exists."
Else
    MsgBox "File doesn't exist."
End If

End Sub

This is the one I like:

Option Explicit

Enum IsFileOpenStatus
    ExistsAndClosedOrReadOnly = 0
    ExistsAndOpenSoBlocked = 1
    NotExists = 2
End Enum


Function IsFileReadOnlyOpen(FileName As String) As IsFileOpenStatus

With New FileSystemObject
    If Not .FileExists(FileName) Then
        IsFileReadOnlyOpen = 2  '  NotExists = 2
        Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
    End If
End With

Dim iFilenum As Long
Dim iErr As Long
On Error Resume Next
    iFilenum = FreeFile()
    Open FileName For Input Lock Read As #iFilenum
    Close iFilenum
    iErr = Err
On Error GoTo 0

Select Case iErr
    Case 0: IsFileReadOnlyOpen = 0 'ExistsAndClosedOrReadOnly = 0
    Case 70: IsFileReadOnlyOpen = 1 'ExistsAndOpenSoBlocked = 1
    Case Else: IsFileReadOnlyOpen = 1 'Error iErr
End Select

End Function    'IsFileReadOnlyOpen

answered Jul 21, 2012 at 13:52

whytheq's user avatar

whytheqwhytheq

34k64 gold badges170 silver badges265 bronze badges

4

Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function

Works very well, almost, at my site. If I call it with «» the empty string, Dir returns «connection.odc«!! Would be great if you guys could share your result.

Anyway, I do like this:

Function FileExists(fullFileName As String) As Boolean
  If fullFileName = "" Then
    FileExists = False
  Else
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
  End If
End Function

answered Oct 22, 2015 at 11:12

Joachim Brolin's user avatar

1

Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function

answered Jun 14, 2015 at 2:09

Ronnie Royston's user avatar

Ronnie RoystonRonnie Royston

16k6 gold badges73 silver badges88 bronze badges

0

I’m not certain what’s wrong with your code specifically, but I use this function I found online (URL in the comments) for checking if a file exists:

Private Function File_Exists(ByVal sPathName As String, Optional Directory As Boolean) As Boolean
    'Code from internet: http://vbadud.blogspot.com/2007/04/vba-function-to-check-file-existence.html
    'Returns True if the passed sPathName exist
    'Otherwise returns False
    On Error Resume Next
    If sPathName <> "" Then

        If IsMissing(Directory) Or Directory = False Then

            File_Exists = (Dir$(sPathName) <> "")
        Else

            File_Exists = (Dir$(sPathName, vbDirectory) <> "")
        End If

    End If
End Function

answered Jul 20, 2012 at 6:31

Dan's user avatar

DanDan

44.9k17 gold badges88 silver badges157 bronze badges

2

Very old post, but since it helped me after I made some modifications, I thought I’d share. If you’re checking to see if a directory exists, you’ll want to add the vbDirectory argument to the Dir function, otherwise you’ll return 0 each time. (Edit: this was in response to Roy’s answer, but I accidentally made it a regular answer.)

Private Function FileExists(fullFileName As String) As Boolean
    FileExists = Len(Dir(fullFileName, vbDirectory)) > 0
End Function

answered Dec 19, 2018 at 3:55

Word Nerd's user avatar

based on other answers here I’d like to share my one-liners that should work for dirs and files:

  • Len(Dir(path)) > 0 or Or Len(Dir(path, vbDirectory)) > 0  'version 1 - ... <> "" should be more inefficient generally
    
    • (just Len(Dir(path)) did not work for directories (Excel 2010 / Win7))
  • CreateObject("Scripting.FileSystemObject").FileExists(path)  'version 2 - could be faster sometimes, but only works for files (tested on Excel 2010/Win7)
    

as PathExists(path) function:

Public Function PathExists(path As String) As Boolean
    PathExists = Len(Dir(path)) > 0 Or Len(Dir(path, vbDirectory)) > 0
End Function

answered Aug 12, 2019 at 9:21

Andreas Covidiot's user avatar

Andreas CovidiotAndreas Covidiot

4,1785 gold badges50 silver badges95 bronze badges

 

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.

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