为了账号安全,请及时绑定邮箱和手机立即绑定

使用VBA检查文件是否存在

使用VBA检查文件是否存在

慕桂英4014372 2019-10-30 10:26:25
Sub test()thesentence = InputBox("Type the filename with full extension", "Raw Data File")Range("A1").Value = thesentenceIf Dir("thesentence") <> "" Then    MsgBox "File exists."Else    MsgBox "File doesn't exist."End IfEnd Sub在这种情况下,当我从输入框中提取文本值时,它不起作用。但是,如果"the sentence"从If中删除Dir()并将其替换为代码中的实际名称,则它可以工作。有人可以帮忙吗?
查看完整描述

3 回答

?
largeQ

TA贡献2039条经验 获得超7个赞

请注意,您的代码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


查看完整回答
反对 回复 2019-10-30
?
料青山看我应如是

TA贡献1772条经验 获得超8个赞

从@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


查看完整回答
反对 回复 2019-10-30
  • 3 回答
  • 0 关注
  • 803 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信