有没有办法使用if ...然后进行错误处理(没有On Error ...或GoTo !!!!)?
我有以下代码,但它仍然停留在if语句中。
Sub test()
If IsError(Workbooks.Open("C:\Users\Desktop\Test\journals.xlsx")) = True Then
'Do something
End If
End Sub
谢谢!
答案 0 :(得分:4)
您可以使用Dir()
功能
If Dir("C:\Users\Desktop\Test\journals.xlsx") = "" Then
'do something
Else
Workbooks.Open "C:\Users\Desktop\Test\journals.xlsx"
End If
答案 1 :(得分:3)
您可以关闭错误处理,然后检查是否从尝试打开工作簿时生成了错误编号。
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
答案 2 :(得分:2)
最简单的答案是否定的,预计你会以某种方式使用On Error:
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")