I frequently need to run queries in Access dividing one column by another and I get sick of always having to put the division inside an iif() statement to try and trap out zero values to avoid division by zero errors. So I wrote the following function:
so for example:
safeDiv(10,5) = 2
safeDiv(10,0) = Null
safeDiv(10,0,0) = 0
works pretty well, except the resulting column is a text field. I tried defining the function as Double, but then the function crashes if I try to assign Null to it. Is there any way to make the successful division be a number but still allow the failures to be null?
Thanks,
Johnny Geo
Code:
Function safeDiv(numerator As Variant, denominator As Variant, Optional divByZero As Variant = Null)
If IsNull(denominator) Or denominator = 0 Then
safeDiv = divByZero
Else
If IsNull(numerator) Then
safeDiv = 0
Else
safeDiv = numerator / denominator
End If
End If
Exit Function
End Function
so for example:
safeDiv(10,5) = 2
safeDiv(10,0) = Null
safeDiv(10,0,0) = 0
works pretty well, except the resulting column is a text field. I tried defining the function as Double, but then the function crashes if I try to assign Null to it. Is there any way to make the successful division be a number but still allow the failures to be null?
Thanks,
Johnny Geo