View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Peter T Peter T is offline
external usenet poster
 
Posts: 5,600
Default How to return an error code from a function

Not sure why you say 'err' can't be passed back to the caller, simply

MySqrt = err
or as an additional argument

If you declare err As Long rather than as a boolean would enable you to pass
more in the way of information, eg the error number itself

In passing, although worksheet functions are extremely efficient in cells
the overhead of calling them in VBA makes them relatively slow, where viable
better to roll your own, eg

result = X ^ (1 / nRoot)

maybe include the root as an argument,
(args, Optional nRoot as Long = 2)

BTW, your 'Exit Function' is redundant

Regards,
Peter T




"deltaquattro" wrote in message
...
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