Home » excel » vba – An example where a variable of type "Error" is declared & used

vba – An example where a variable of type "Error" is declared & used

Posted by: admin May 14, 2020 Leave a comment

Questions:

I would like to make a test where a variable of type Error is declared, and used later in a VBA program. I have written =1/0 in cell (5,6) of the active sheet, therefore it has value #DIV/0!, then I try to run the following code:

Sub try()
   Dim x As Error
   y = ActiveSheet.Cells(5, 6).Value
   MsgBox TypeName(y)
   x = ActiveSheet.Cells(5, 6).Value
End Sub

The MsgBox does print Error for y, however, an error is raised in the line of the assignment to x: Run-time error "91": Object variable or With block variable not set.

Could anyone tell me what is wrong here, or gives me another example where a variable or type Error is declared & used?

How to&Answers:

an error in a cell is an error value, not an Error object

to use an error object:

   Dim x As Error
   Dim n As Long
   ActiveCell.Formula = "=1/0"
   For n = xlEvaluateToError To xlInconsistentListFormula
      Set x = ActiveCell.Errors(n)
      If x.Value Then MsgBox "Error in cell"
   Next n

Answer:

To retrieve the error message from the cell:

Sub try()
    Dim x As String
    Dim y As Variant
    y = ActiveSheet.Cells(5, 6).Value
    MsgBox TypeName(y)
    If TypeName(y) = "Error" Then
        x = ActiveSheet.Cells(5, 6).Text
        MsgBox x
    End If
End Sub

You would use Error as a function to retrieve the error message if all you had was the error number.