Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If IsError in VBA?

Tags:

excel

vba

Is it possible to use something with similar functionality as Iferror(value, value_if_error) or Iserror(value) in VBA?

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!

like image 579
user1283776 Avatar asked Dec 01 '22 18:12

user1283776


2 Answers

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
like image 189
chris neilsen Avatar answered Dec 10 '22 13:12

chris neilsen


You can call all worksheet functions using Application.WorksheetFunction.IsError(args)

You could also try doing the calculation in a cell directly and query it's value. For example, very 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
like image 35
JustinJDavies Avatar answered Dec 10 '22 14:12

JustinJDavies