使用VBA检查文件是否存在


82
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

在这种情况下,当我从输入框中提取文本值时,它不起作用。但是,如果"the sentence"从If中删除Dir()并将其替换为代码中的实际名称,则它可以工作。有人可以帮忙吗?

Answers:


142

请注意,您的代码Dir("thesentence")应包含Dir(thesentence)

将您的代码更改为此

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

1
它部分地帮助了我,我认为当我使用此代码编译器时,并未将“语句”视为目录,因此在使用以下代码之前,我只使用了另一行代码:<code> Dim Path as String Dim Directory as String Path = InitialPath& “ \”&Date $ Directory = Dir(Path,vbDirectory)</ code>当我在If Dir(Directory)<>“”下使用** Directory **可变字符串时,它工作得很好
muhammad tayyab

19

使用OfficeFileDialog对象让用户从文件系统中选择一个文件。在您的VB项目或VBA编辑器中添加参考,Microsoft Office Library然后查看帮助。这比让人们进入完整的道路要好得多。

这是一个示例,msoFileDialogFilePicker用于允许用户选择多个文件。您也可以使用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

有很多选项,因此您需要查看完整的帮助文件以了解所有可能的方法。您可以从Office 2007 FileDialog对象开始(当然,您需要找到所使用版本的正确帮助)。


1
+1更好,因为这是excel Application.FileDialog(msoFileDialogOpen)
Alex K.

18

对@UberNubIsTrue中的fileExists的更正:

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

编辑:缩短版本

' 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

2
为什么代码多次测试同一文件名(s_directory中的每个文件一次)?重复此测试没有意义。您将注意到循环代码未使用循环变量(obj_file)。
Grantnz

1
@grantnz确实!我已经完成了懒惰的复制/粘贴并进行了调整,直到它起作用为止。缩短的版本在上面。谢谢。
amackay11年

是否有人注意到该测试有时会报告误报,即,即使文件系统中不存在文件,它也会返回“ True”。在我的应用程序中,如果有提示,我将检查网络中服务器中文件的存在。
pablete

6

只是摆脱那些语音标记

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

这是我喜欢的一个:

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

3
我以前从未听说过“语音标记”。奇怪。我认为这有点用词不当。很多东西都需要引号,但不是语音。
ErikE 2012年

4
@ErikE +1可以很好地观察...图片在这里
whytheq 2012年

1
显然,“语音标记”是“引号”的非正式版本。
ErikE 2012年

@ErikE ...我知道还是我说“我知道”
whytheq 2012年

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

在我的网站上几乎可以正常运行。如果我使用“”空字符串来调用它,Dir将返回“ connection.odc ”!如果你们可以分享您的结果,那就太好了。

无论如何,我确实这样:

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

1
旧帖子,但看起来像是dir("")为您提供了当前目录中第一个文件的名称。您的情况是一个名为的文件connection.odc
科里

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

3

我不确定您的代码具体有什么问题,但是我使用在网上找到的此功能(注释中的URL)来检查文件是否存在:

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

1
如果您提供路径并且不知道它是否是目录,则将返回true。如果您要测试路径是否仅是文件,则无法100%使用。? dir$("C:\Users\Chloe\AppData\Local\Temp\")将提供该目录中的第一个文件,并且不等于“”,因此,即使您将Directory参数设置为off或将其设置为false ,它也将返回true 。
Chloe 2014年

@Chloe我猜想是假设您将指定文件扩展名和文件名,因此在这种情况下,实际上不会成为目录的歧义。但是可以肯定,它可能更强大。这仅取决于您所需解决方案的深度。但它的确为案件工作规定由OP

1

很老的帖子,但是由于我做了一些修改后对我有帮助,所以我认为我愿意分享。如果要检查目录是否存在,则需要将vbDirectory参数添加到Dir函数中,否则将0每次返回。(编辑:这是对Roy的回答,但我无意中将其作为常规回答。)

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

1

根据这里的其他答案,我想分享一下适用于目录和文件的单行代码:

  • Len(Dir(path)) > 0 or Or Len(Dir(path, vbDirectory)) > 0  'version 1 - ... <> "" should be more inefficient generally
    
    • (仅对Len(Dir(path))目录不起作用(Excel 2010 / Win7))
  • CreateObject("Scripting.FileSystemObject").FileExists(path)  'version 2 - could be faster sometimes, but only works for files (tested on Excel 2010/Win7)
    

作为PathExists(path)功能:

Public Function PathExists(path As String) As Boolean
    PathExists = Len(Dir(path)) > 0 Or Len(Dir(path, vbDirectory)) > 0
End Function
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.