使用VBA检查文件是否存在

Din*_*oel 78 excel vba

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
Run Code Online (Sandbox Code Playgroud)

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

Cyl*_*ian 130

请注意您的代码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
Run Code Online (Sandbox Code Playgroud)


Eri*_*ikE 18

使用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
Run Code Online (Sandbox Code Playgroud)

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


ama*_*y11 16

从@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
Run Code Online (Sandbox Code Playgroud)

编辑:缩短版本

' 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
Run Code Online (Sandbox Code Playgroud)

  • 为什么代码多次测试相同的文件名(对于s_directory中的每个文件一次)?重复这个测试是没有意义的.您会注意到循环代码不使用循环变量(obj_file). (2认同)

why*_*heq 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
Run Code Online (Sandbox Code Playgroud)

这是我喜欢的人:

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
Run Code Online (Sandbox Code Playgroud)

  • @ErikE +1获得良好观察... [图片在这里](https://www.google.com/search?q=speech+marks&hl=zh-CN&rlz=1C1CHRG_en&prmd=imvns&tbm=isch&tbo=u&source=univ&sa=X&ei=UtQKUPS-IMqM0wWg -cyyCg&VED = 0CHoQsAQ&BIW = 1280&波黑= 685) (4认同)
  • 我以前从未听说过"语音标记".奇怪.在我看来,这种用词不当.很多东西需要引用但不是语音. (3认同)

小智 6

Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
Run Code Online (Sandbox Code Playgroud)

几乎在我的网站上工作得非常好.如果我用""空字符串调用它,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
Run Code Online (Sandbox Code Playgroud)


Ron*_*ton 5

Function FileExists(fullFileName As String) As Boolean
    FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
Run Code Online (Sandbox Code Playgroud)