使用 if...then VBA 进行错误处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41442211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error handling with if...then VBA
提问by Vinnie
Is there any way to use if...then for error handling (without On Error... or GoTo!!!!)?
有没有办法使用 if...then 进行错误处理(没有 On Error... 或 GoTo!!!)?
I have the below code, but it's stuck at the if statement.
我有下面的代码,但它卡在 if 语句中。
Sub test()
If IsError(Workbooks.Open("C:\Users\Desktop\Test\journals.xlsx")) = True Then
'Do something
End If
End Sub
Thanks!
谢谢!
回答by user3598756
you could use Dir()
function
你可以使用Dir()
函数
If Dir("C:\Users\Desktop\Test\journals.xlsx") = "" Then
'do something
Else
Workbooks.Open "C:\Users\Desktop\Test\journals.xlsx"
End If
回答by luke_t
You can turn off error handling and then check if an error number was generated from the attempt at opening the workbook.
您可以关闭错误处理,然后检查是否在尝试打开工作簿时生成了错误编号。
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
Edit 1: Since you are already doing so nicely, directly setting it to a wb
object, why not use it's capabilities ?
编辑 1:既然你已经做得很好了,直接将它设置为一个wb
对象,为什么不使用它的功能呢?
If wb Is Nothing Then
回答by Absinthe
The simplest answer is no, it's expected that you'll use On Error in some fashion, either:
最简单的答案是否定的,预计您将以某种方式使用 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
or in a traditional error handler:
或在传统的错误处理程序中:
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
However, you can use the FileSystemObjectto test if a file exists:
但是,您可以使用FileSystemObject来测试文件是否存在:
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
fileExists = fso.fileExists("C:\Users\Desktop\Test\journals.xlsx")