Looking for a piece of code to replace an error with 0

S

Shawna

I would like to enter a small piece of code that will return a zero if an
equation returns a number error. I am dividing two numbers and occassionally
the numbers are both zero.
 
A

Adam O'Neil

You could do something like this:

Function SafeDivide(vNumerator, vDenominator) As Double
On Error Resume Next

SafeDivide = vNumerator / vDenominator

If (Err.Number <> 0) Then
SafeDivide = 0
End If

End Function

The idea is that if any error occurs (no matter what it is), the function
will return 0.

adam
 
S

Sergey Poberezovskiy

This will work fine in a query, in code this may generate
Division by zero error. In code IIF function evaluates
both True and False part - hence the error. So to get the
result in code you will need to use the full If Then Else
syntax:

If Divisor = 0 Then
result = 0
Else
result = Numerator/Divisor
End If
 
Top