Question : Can a VBA function return an error code such as #DIV/0

How can I get a VBA function to return an error code such as #DIV/0! or #ERR - I can return Null, but this is interpreted as 0, so does not achieve my goals.

The VBA function will be accessed within a cell formula.

Thanks!

Answer : Can a VBA function return an error code such as #DIV/0

yes, and it is usually the way to manage this situation.
First, have the function return a variant. Then, manage the error situation:
- if error, choose a member of the enum xlCVError, eg xlErrDiv0
-  convert it as an error using the CvErr function
- return it as the result of the function

eg: dividing num1 by num2
Function Divide(Num1 As Double, Num2 As Double) As Variant
   If Num2 = 0 Then
      Divide = CVErr(XlCVError.xlErrDiv0)
   Else
      Divide = Num1 / Num2
   End If
End Function

Regards,
Sebastien
Random Solutions  
 
programming4us programming4us