Excel 使用VBA检查文件是否存在 子测试() 内容=输入框(“键入具有完整扩展名的文件名”,“原始数据文件”) 范围(“A1”)。值=内容 如果是Dir(“thesentence”)“那么 MsgBox“文件已存在。” 其他的 MsgBox“文件不存在。” 如果结束 端接头

Excel 使用VBA检查文件是否存在 子测试() 内容=输入框(“键入具有完整扩展名的文件名”,“原始数据文件”) 范围(“A1”)。值=内容 如果是Dir(“thesentence”)“那么 MsgBox“文件已存在。” 其他的 MsgBox“文件不存在。” 如果结束 端接头,excel,vba,Excel,Vba,在这种情况下,当我从输入框中拾取文本值时,它不起作用。但是,如果从IfDir()中删除“句子”,并将其替换为代码中的实际名称,则它可以工作。有人能帮忙吗?注意您的代码包含Dir(“内容”),应该是Dir(内容) 将代码更改为此 Sub test() thesentence = InputBox("Type the filename with full extension", "Raw Data File") Range("A1").Value = thesentence If Dir("t

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

注意您的代码包含
Dir(“内容”)
,应该是
Dir(内容)

将代码更改为此

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
子测试()
内容=输入框(“键入具有完整扩展名的文件名”,“原始数据文件”)
范围(“A1”)。值=内容
如果目录(内容)“,则
MsgBox“文件已存在。”
其他的
MsgBox“文件不存在。”
如果结束
端接头

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

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
Private Function File_作为布尔值存在(ByVal sPathName作为字符串,可选目录作为布尔值)
“来自互联网的代码:http://vbadud.blogspot.com/2007/04/vba-function-to-check-file-existence.html
'如果传递的sPathName存在,则返回True
否则返回False
出错时继续下一步
如果是“我”,那么
如果IsMissing(Directory)或Directory=False,则
文件_Exists=(Dir$(sPathName)”)
其他的
文件_Exists=(Dir$(sPathName,vbDirectory)“”)
如果结束
如果结束
端函数

使用Office
文件对话框
对象让用户从文件系统中选择文件。在VB项目或VBA编辑器中将引用添加到Microsoft Office库中,然后查看帮助。这比让人们进入完整的路径要好得多

下面是一个使用
msoFileDialogFilePicker
允许用户选择多个文件的示例。您也可以使用
msoFileDialogOpen

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

有很多选项,因此您需要查看完整的帮助文件以了解所有可能的内容。您可以从开始(当然,您需要为您正在使用的版本找到正确的帮助)。

只需去除这些语音标记即可

'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

对@UberNubIsTrue中存在的文件的更正:

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
编辑:缩短版

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
在我的网站上工作得非常好。如果我用空字符串“”调用它,Dir将返回“connection.odc”!!如果你们能分享你们的结果,那就太好了

无论如何,我喜欢这样:

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

非常旧的帖子,但在我做了一些修改后,它对我很有帮助,我想我会和大家分享。如果要检查目录是否存在,则需要将vbDirectory参数添加到Dir函数中,否则每次都将返回
0
。(编辑:这是对罗伊回答的回应,但我意外地将其作为常规回答。)


基于这里的其他答案,我想与大家分享我的一行代码,应该适用于dir和文件

由于路径存在(路径)功能:

CreateObject("Scripting.FileSystemObject").FileExists(path)  'version 2 - could be faster sometimes, but only works for files (tested on Excel 2010/Win7)

+1更好,因为这是excel Application.FileDialog(msoFileDialogOpen),我以前从未听说过“语音标记”。奇怪。在我看来,这有点用词不当。很多东西都需要引用,但不是言语。@ErikE+1用于观察。。。显然,“语音标记”是“引号”的非正式版本。@ErikE…我知道,或者说我说“我知道”,为什么代码要多次测试同一个文件名(对s_目录中的每个文件测试一次)?重复这个测试没有意义。您会注意到循环变量(obj_文件)没有被循环代码使用。@grantnz确实如此!我已经做了懒惰的复制/粘贴和调整,直到它的工作。上面是缩短版。谢谢。有没有人注意到,有时候这个测试会报告假阳性,即即使文件系统中不存在文件,它也会返回“True”。在我的应用程序中,我会检查网络服务器中是否存在一个文件,如果这给了你一个提示。如果你给出一个路径,并且不知道它是否是一个目录,这将返回true。如果要测试路径是否仅为文件,则无法100%运行<代码>?dir$(“C:\Users\Chloe\AppData\Local\Temp\”)将给出该目录中的第一个文件,它将不等于“”,因此,即使您关闭
目录
参数或将其设置为false,它也将返回true。@Chloe我猜这是假设您将指定一个文件扩展名以及文件名,因此目录的模糊性在这种情况下并不真正适用。但可以肯定的是,它可能更强大。这取决于你需要多深的解决方案。但它确实对OPIt指定的情况有所帮助,我认为当我使用这个代码编译器没有考虑“目录”作为一个目录,所以我只使用了另外一行代码,如果:<代码>昏暗路径作为字符串模糊目录作为字符串路径=初始化路径和“\\”和日期$Directory = dir(路径,vbDirectory)当我在If Dir(Directory)“”下使用**Directory**变量字符串时,它在旧帖子中运行良好,但它看起来像是
Dir(“”)
提供了当前目录中第一个文件的名称。在您的例子中,它是一个名为
connection.odc
的文件。
Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
Function FileExists(fullFileName As String) As Boolean
  If fullFileName = "" Then
    FileExists = False
  Else
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
  End If
End Function
Private Function FileExists(fullFileName As String) As Boolean
    FileExists = Len(Dir(fullFileName, vbDirectory)) > 0
End Function
Len(Dir(path)) > 0 or Or Len(Dir(path, vbDirectory)) > 0  'version 1 - ... <> "" should be more inefficient generally
CreateObject("Scripting.FileSystemObject").FileExists(path)  'version 2 - could be faster sometimes, but only works for files (tested on Excel 2010/Win7)
Public Function PathExists(path As String) As Boolean
    PathExists = Len(Dir(path)) > 0 Or Len(Dir(path, vbDirectory)) > 0
End Function