【问题标题】:Check if the file exists using VBA使用 VBA 检查文件是否存在
【发布时间】:2012-07-19 09:49:29
【问题描述】:
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

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

【问题讨论】:

    标签: excel vba


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      很老的帖子,但是因为在我做了一些修改后它对我有帮助,所以我想我会分享。如果要检查目录是否存在,则需要将 vbDirectory 参数添加到 Dir 函数,否则每次都会返回 0。 (编辑:这是对罗伊的回答的回应,但我不小心把它变成了常规答案。)

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

      【讨论】:

        【解决方案3】:
        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
        

        【讨论】:

        • 旧帖子,但看起来dir("") 为您提供了当前目录中第一个文件的名称。在您的情况下,它是一个名为 connection.odc 的文件。
        【解决方案4】:
        Function FileExists(fullFileName As String) As Boolean
            FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
        End Function
        

        【讨论】:

          【解决方案5】:

          只要去掉那些语音标记

          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
          

          【讨论】:

          • 我以前从未听说过“语音标记”。奇怪的。在我看来有点用词不当。很多东西都需要引号,但不是语音。
          • @ErikE +1 进行很好的观察...Pictures Here
          • 显然“语音标记”是“引号”的非正式版本。
          • @ErikE ...我知道或者我说“我知道”
          【解决方案6】:

          我不确定您的代码具体有什么问题,但我使用我在网上找到的这个函数(cmets 中的 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
          

          【讨论】:

          • 如果你给出一个路径并且不知道它是否是一个目录,这将返回 true。如果你想测试一个路径是否只是一个文件,这不会 100% 起作用。 ? dir$("C:\Users\Chloe\AppData\Local\Temp\") 将给出该目录中的第一个文件,并且它不会等于 "",因此,即使您将 Directory 参数关闭或将其设置为 false,它也会返回 true。
          • @Chloe 我想这是假设您将指定文件扩展名以及文件名,因此在这种情况下,作为目录的歧义并不真正适用。但可以肯定的是,它可能会更强大。这仅取决于您需要的解决方案有多深。但它确实适用于 OP 指定的情况
          【解决方案7】:

          更正来自@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
          

          编辑:缩短版

          ' 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
          

          【讨论】:

          • 为什么代码要多次测试同一个文件名(s_directory中的每个文件一次)?重复这个测试是没有意义的。你会注意到循环代码没有使用循环变量(obj_file)。
          • @grantnz 确实!我已经完成了懒惰的复制/粘贴并进行了调整,直到它起作用。上面是精简版。谢谢。
          • 有没有人注意到有时这个测试会报告一个误报,即即使文件系统中不存在文件,它也会返回“True”。在我的应用程序中,我会检查我网络上的服务器中是否存在文件,如果这给了你提示的话。
          【解决方案8】:

          使用 Office FileDialog 对象让用户从文件系统中选择一个文件。在您的 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 object 开始(当然,您需要找到您正在使用的版本的正确帮助)。

          【讨论】:

          • +1 好多了,因为这是 excel Application.FileDialog(msoFileDialogOpen)
          【解决方案9】:

          注意您的代码包含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
          

          【讨论】:

          • 它对我有部分帮助Dim Directory as String Path = InitialPath & "\" & Date$ Directory = Dir(Path, vbDirectory) 当我在 If Dir(Directory) "" 下使用** Directory ** 变量字符串时,它运行良好
          猜你喜欢
          • 2013-04-27
          • 1970-01-01
          • 1970-01-01
          • 2017-11-10
          • 1970-01-01
          • 2015-04-19
          • 1970-01-01
          • 2017-02-21
          • 1970-01-01
          相关资源
          最近更新 更多