Есть ли файл в папке 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
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

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 am stepping into a directory of folders and looking into the folders to get particular data each time I find a specific file.

If I go to open the file I am looking for in a folder that it is not in, I get a debug error. So clearly I need to test the directory to see if the file is there and not try to open it if it is not (that is fine, not all the folders have the subject file).

The DIR function is the hands on favorite to test a file’s presence, but because I am using the DIR function to step through the folders, my testing has shown that I cannot use the DIR to test for a specific file in the middle of my code because VBA gets confused where I was in the stepping through the folders.

How can I test for the existence of a known filename without using DIR? I tried the function I found:

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

Unfortunately, I have not figured out how to actually write this into the SUB that I am building. The sample I found (and others similar), but the usually do not make clear what is needed for an aspiring novice. In this case don’t know what would go in LEN and DIR and why the fullfilename would be needed in what looks like a DIM statement (because of the As Boolean). I also find that if I try to put this function within my Subroutine, VBA is just not happy.

What can I try that will work? I just want an IF statement around a function that will tell me if the file exists or not.

 

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?

Понравилась статья? Поделить с друзьями:
  • Есть ли такая программа word
  • Есть ли просто word
  • Есть ли проверка орфографии в excel
  • Есть ли поиск по словам в word
  • Есть ли переменные в excel