2013-05-03 208 views
23

我有这段代码。它应该检查文件是否存在,如果存在则打开它。如果文件存在,它会工作,如果不存在,但是,每当我将文本框留空并单击提交按钮时,它就会失败。我想要的,如果文本框为空,就像显示错误信息一样,如果文件不存在。VBA检查文件是否存在

运行时错误 “1004”

Dim File As String 
File = TextBox1.Value 
Dim DirFile As String 

DirFile = "C:\Documents and Settings\Administrator\Desktop\" & File 
If Dir(DirFile) = "" Then 
    MsgBox "File does not exist" 
Else 
    Workbooks.Open Filename:=DirFile 
End If 
+0

您还没有提供代码的问题部分(即包含提交按钮的表单)。你能分享你的文件吗? – brettdj 2013-05-03 03:52:10

+0

上面的代码是我提交按钮的内容 – 2013-05-03 03:58:29

回答

42

像这样

最好使用一个工作簿变量来提供进一步的控制(如果需要)打开的工作簿的

更新,以测试文件名是一个实际的工作簿 - 这也使得初始勾选冗余时,除了消息的用户比文本框为空

Dim strFile As String 
Dim WB As Workbook 
strFile = Trim(TextBox1.Value) 
Dim DirFile As String 
If Len(strFile) = 0 Then Exit Sub 

DirFile = "C:\Documents and Settings\Administrator\Desktop\" & strFile 
If Len(Dir(DirFile)) = 0 Then 
    MsgBox "File does not exist" 
Else 
On Error Resume Next 
Set WB = Workbooks.Open(DirFile) 
On Error GoTo 0 
If WB Is Nothing Then MsgBox DirFile & " is invalid", vbCritical 
End If 
+1

此方法不是100%可靠的,因为它不会区分文件夹名称和文件夹名称。 – 2015-08-19 11:15:43

+1

@iDevlop我已经走了一步来测试文件名是有效的。 – brettdj 2016-02-26 11:26:44

0

也许它由文件名引起变量

File = TextBox1.Value 

应该

Filename = TextBox1.Value 
+3

这不是一个不好的答案。使用“文件”或任何其他关键字作为变量名已经给很多人造成了麻烦。尽管这不是解决问题的办法,但它仍然是一个很好的观点。 – AnyOneElse 2014-12-17 16:12:22

-5

呦你应该设置一个条件循环来检查TextBox1的值。

If TextBox1.value = "" then 
    MsgBox "The file not exist" 
    Exit sub 'exit the macro 
End If 

希望它能帮助你。

22

使用此功能来检查文件的存在:

Function IsFile(ByVal fName As String) As Boolean 
'Returns TRUE if the provided name points to an existing file. 
'Returns FALSE if not existing, or if it's a folder 
    On Error Resume Next 
    IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory) 
End Function 
+1

既然你有'On Error Resume Next',在你的主线后面我会介绍'On Error GoTo 0',以防止挂起错误。无论如何,我喜欢这种方法,因为可以检查文件的存在而不会意外检查文件夹的存在。 – ZygD 2015-11-18 05:37:55

+1

这是否处理fName既不是文件也不是目录的情况?看起来像@ brettdj和iDevlop的答案是最好的组合:_IsFile =((GetAttr(fName)和vbDirectory)<> vbDirectory)和Len(Dir(DirFile))<> 0_ – riderBill 2015-12-10 03:21:43

+2

进一步调查,似乎_GetAttr(fName )_将引发异常53 - FileNotFoundException,调用Resume Next,并且IsFile将保持其先前值(False)。所以你的函数_does_处理所有的情况。 我可能不会测试它,但它可能比brettdj的运行速度更快,因为它不会调用Dir,它看起来像系统命令(?)一样可疑。从我的C/C++经验来看,调用一个系统命令需要1秒左右的时间,也许还有一秒钟来恢复可执行文件。 非常好!我以前投票答复你的答案。我不明白为什么这不是最佳的投票选择。 – riderBill 2015-12-10 05:13:34

12

为了检查是否存在一个也可以使用(同时适用于文件和文件夹)

Not Dir(DirFile, vbDirectory) = vbNullString 

结果是True如果一个文件或目录存在。

例子:

If Not Dir("C:\Temp\test.xlsx", vbDirectory) = vbNullString Then 
    MsgBox "exists" 
Else 
    MsgBox "does not exist" 
End If 
0

我会在那儿,然后扔鸭这一点。 检查文件是否存在的常见原因是在尝试打开文件时避免出现错误。如何使用错误处理程序来处理:

Function openFileTest(filePathName As String, ByRef wkBook As Workbook, _ 
         errorHandlingMethod As Long) As Boolean 
'Returns True if filePathName is successfully opened, 
'  False otherwise. 
    Dim errorNum As Long 

'*************************************************************************** 
' Open the file or determine that it doesn't exist. 
    On Error Resume Next: 
    Set wkBook = Workbooks.Open(fileName:=filePathName) 
    If Err.Number <> 0 Then 
     errorNum = Err.Number 
     'Error while attempting to open the file. Maybe it doesn't exist? 
     If Err.Number = 1004 Then 
'*************************************************************************** 
     'File doesn't exist. 
     'Better clear the error and point to the error handler before moving on. 
     Err.Clear 
     On Error GoTo OPENFILETEST_FAIL: 
     '[Clever code here to cope with non-existant file] 
     '... 
     'If the problem could not be resolved, invoke the error handler. 
     Err.Raise errorNum 
     Else 
     'No idea what the error is, but it's not due to a non-existant file 
     'Invoke the error handler. 
     Err.Clear 
     On Error GoTo OPENFILETEST_FAIL: 
     Err.Raise errorNum 
     End If 
    End If 

    'Either the file was successfully opened or the problem was resolved. 
    openFileTest = True 
    Exit Function 

OPENFILETEST_FAIL: 
    errorNum = Err.Number 
    'Presumabley the problem is not a non-existant file, so it's 
    'some other error. Not sure what this would be, so... 
    If errorHandlingMethod < 2 Then 
     'The easy out is to clear the error, reset to the default error handler, 
     'and raise the error number again. 
     'This will immediately cause the code to terminate with VBA's standard 
     'run time error Message box: 
     errorNum = Err.Number 
     Err.Clear 
     On Error GoTo 0 
     Err.Raise errorNum 
     Exit Function 

    ElseIf errorHandlingMethod = 2 Then 
     'Easier debugging, generate a more informative message box, then terminate: 
     MsgBox "" _ 
      & "Error while opening workbook." _ 
      & "PathName: " & filePathName & vbCrLf _ 
      & "Error " & errorNum & ": " & Err.Description & vbCrLf _ 
      , vbExclamation _ 
      , "Failure in function OpenFile(), IO Module" 
     End 

    Else 
     'The calling function is ok with a false result. That is the point 
     'of returning a boolean, after all. 
     openFileTest = False 
     Exit Function 
    End If 

End Function 'openFileTest()