有沒有什麼方法可以使用if ...然後用於錯誤處理(沒有On Error ...或GoTo !!!!)?錯誤處理if ...然後VBA
我有下面的代碼,但它卡在if語句。
Sub test()
If IsError(Workbooks.Open("C:\Users\Desktop\Test\journals.xlsx")) = True Then
'Do something
End If
End Sub
謝謝!
有沒有什麼方法可以使用if ...然後用於錯誤處理(沒有On Error ...或GoTo !!!!)?錯誤處理if ...然後VBA
我有下面的代碼,但它卡在if語句。
Sub test()
If IsError(Workbooks.Open("C:\Users\Desktop\Test\journals.xlsx")) = True Then
'Do something
End If
End Sub
謝謝!
你可以使用Dir()
功能
If Dir("C:\Users\Desktop\Test\journals.xlsx") = "" Then
'do something
Else
Workbooks.Open "C:\Users\Desktop\Test\journals.xlsx"
End If
這是完美的,謝謝! – Vinnie
不客氣。然後,您可能想要將答案標記爲已接受。謝謝! – user3598756
您可以關閉錯誤處理,然後檢查是否從嘗試打開工作簿時生成錯誤編號。
Dim wb As Workbook
On Error Resume Next
Set wb = Workbooks.Open("C:\Users\Desktop\Test\journals.xlsx")
If Err.Number > 0 Then
'' there was an error with opening the workbook
End If
On Error GoTo 0
編輯1:既然你已經這樣做很好,它直接設置爲wb
對象,爲什麼不使用它的功能?
If wb Is Nothing Then
允許我提供替代方案, –
最簡單的答案是否定的,它的預期,你會以某種方式使用上的錯誤,或者:
On error resume next
Workbooks.Open("C:\Users\Desktop\Test\journals.xlsx")
If Err.Number <> 0 then
' the workbook is not at that location
Err.Clear
On Error Goto 0
End If
或在傳統錯誤處理程序:
errhandler:
If Err.Number <> 0 then
If Err.Number = 1004 Then
' the workbook is not at that location, do something about it, then resume next
End If
End If
但是,您可以使用FileSystemObject測試文件是否存在:
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
fileExists = fso.fileExists("C:\Users\Desktop\Test\journals.xlsx")
的[好的模式對於VBA錯誤處理(可能的複製http://stackoverflow.com/questions/1038006/good-patterns- for-vba-error-handling) – vacip
我想在沒有On Error語句的情況下解決它。 – Vinnie
使用On Error語句完成VBA中的錯誤處理。期。在某些情況下,您可以找到問題特定的解決方案。也許你需要更改標題,因爲它是誤導性的;這不是錯誤處理,這是檢查是否存在文件。 (哪個問題在這裏也有10000個答案......) – vacip