如果在 VBA 中出现错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18562252/
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
If IsError in VBA?
提问by user1283776
Is it possible to use something with similar functionality as Iferror(value, value_if_error) or Iserror(value) in VBA?
是否可以在 VBA 中使用与 Iferror(value, value_if_error) 或 Iserror(value) 类似的功能?
I tried to write:
我试着写:
If IsError(Cells(i, c) / curr) Then
'CODE BLOCK 1
else
'CODE BLOCK 2
end if
But VBA tells me that I have division by zero error when it tries to run the if-statement. It throws me into debug. But this is just the type of thing I want to trigger CODE BLOCK 1!
但是 VBA 告诉我,当它尝试运行 if 语句时,我有除以零错误。它让我陷入调试。但这正是我想要触发代码块 1 的类型!
回答by chris neilsen
The usual way to handle this would be
通常的处理方法是
i = 0
On Error Resume Next
n = 1 / i
If Err.Number <> 0 Then
'Handle error - code block 1
Err.Clear
On Error GoTo 0
Else
On Error GoTo 0
' No error - code block 2
End If
回答by JustinJDavies
You can call all worksheet functions using Application.WorksheetFunction.IsError(args)
您可以使用调用所有工作表函数 Application.WorksheetFunction.IsError(args)
You could also try doing the calculation in a cell directly and query it's value. For example, very hacky:
您也可以尝试直接在单元格中进行计算并查询其值。例如,非常hacky:
Sub asdf()
Dim ws As New Worksheet
Set ws = ActiveSheet
Dim i As Double
i = 0
ws.Range("A2").Formula = "=iserror(A1 / " & i & ")"
If ws.Range("A2").Value Then
Debug.Print "Error caught"
Else
Debug.Print "No error"
End If
End Subu