View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
Dave Peterson Dave Peterson is offline
external usenet poster
 
Posts: 35,218
Default How to return an error code from a function

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

deltaquattro wrote:

Hi,

after some discussions on the ng I decided to keep input data checking
inside my functions. This prompts the problem of how to return an
error code from the function: for example

Function MySqrt(x as Double) As Double
Dim err As Boolean
If x <0 Ihen
err=True
Exit Function
Else
err=False
x = Application.Worksheetfunction.sqrt(x)
End If
End Function

However, err cannot be passed back to the caller! I've read about
different workarounds, and I would like to know your opinion on them,
or just which is your approach:

1. convert the Function to a Sub (easiest, but maybe slower?)
2. pass err ByRef (best?)
3. declare Function As Variant. Variant variables, however, cause a
slowdown of the code, so would this be any faster than 1. ?
4. use global variables (I'd rather not).

Thanks in advance,

Best Regards,

Sergio Rossi


--

Dave Peterson