How to return an error code from a function
Hi, Dave,
I implemented your code with my modification (check on "Is Nothing")
and it seems to be working great. Thanks!!!
Best Regards,
deltaquattro
On 5 Feb, 18:00, Dave Peterson wrote:
What do you mean by an error code? *
Do you mean the err.number? *If yes, then you have to do something special since
err.numbers would be the sqareroot of a number.
Maybe you could do something like:
Option Explicit
Function mySqrt(x As Double) As Double
* * Dim myVal As Variant
* * On Error Resume Next
* * myVal = Sqr(x)
* * If Err.Number < 0 Then
* * * * 'are all the possible errors positive???
* * * * 'I'm not sure
* * * * mySqrt = -Abs(Err.Number)
* * * * Err.Clear
* * Else
* * * * mySqrt = myVal
* * End If
* * On Error GoTo 0
End Function
Sub testme()
* * Dim res As Double
* * res = mySqrt(-123)
* * If res < 0 Then
* * * * On Error Resume Next
* * * * Err.Raise Number:=-res
* * * * With Err
* * * * * *MsgBox .Number & vbLf & .Description
* * * * End With
* * Else
* * * * MsgBox res
* * End If
End Sub
Or you could pass the error object, too:
Option Explicit
Function mySqrt(x As Double, myError As ErrObject) As Double
* * Dim myVal As Variant
* * On Error Resume Next
* * myVal = Sqr(x)
* * If Err.Number < 0 Then
* * * * Set myError = Err
* * * * mySqrt = -1
* * Else
* * * * mySqrt = myVal
* * End If
End Function
Sub testme()
* * Dim res As Double
* * Dim myRetError As ErrObject
* * res = mySqrt(-1, myRetError)
* * If res = -1 Then
* * * * With myRetError
* * * * * * MsgBox .Number & vbLf & .Description
* * * * End With
* * Else
* * * * MsgBox res
* * End If
End Sub
|