2013-05-03 213 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()