Question

I have a tablix box that has a division expression. When dividing by zero or nulls I get #Error displayed in my report. I tried to create an IIF statement and tested with static values. This verified my syntax was correct but I still see the error on my reports.

Report Preview

=IIF(Sum(Fields!CY_Dollars.Value)=0, 0, (Sum(Fields!CY_Dollars.Value) - Sum(Fields!PY_Dollars.Value))/(Sum(Fields!PY_Dollars.Value)))

So I'm taking Current year dollars, subtracting Previous year dollars, and dividing that total by previous year dollars to get the percentage change. Is there a trick to this that I'm not getting?!

Was it helpful?

Solution

You can add a function to your report code that handles the divide by zero condition, this makes it a bit easier to implement in multiple cells, e.g.

Public Function Divider (ByVal Dividend As Double, ByVal Divisor As Double)
If IsNothing(Divisor) Or Divisor = 0
  Return 0
Else
  Return Dividend/Divisor
End If
End Function 

You can then call this in a cell like so:

=Code.Divider(Fields!FieldA.Value, Fields!FieldB.Value)

OTHER TIPS

I suspect you're running into the issue where SSRS doesn't actually short circuit an IIF statement; even though you're checking for 0, you're still going to hit a divide by zero error.

Try something like:

=IIf(Sum(Fields!PY_Dollars.Value) = 0, 0, Sum(Fields!CY_Dollars.Value) - Sum(Fields!PY_Dollars.Value))
  / IIf(Sum(Fields!PY_Dollars.Value) = 0, 1, Sum(Fields!PY_Dollars.Value))

Using two IIf statements means you avoid the error by using the equation 0/1 when Sum(Fields!PY_Dollars.Value) = 0, thus just returning 0.

Also note that the above expression is checking Sum(Fields!PY_Dollars.Value) = 0, but yours is checking Sum(Fields!CY_Dollars.Value) = 0 - the denominator needs the zero check here.

To avoid the overhead of maintaining code, the solution below feels tidiest to me. It avoids the division by zero in the denominator by adding the smallest possible Double value to it (Double.Epsilon, which is 4.94e-324). This value's way too small to affect the value of the fraction for anything people would use SSRS for. It also avoids nesting IIF functions.

=IIF(Sum(Fields!Denominator.Value)>0, 
     Sum(Fields!Numerator.Value)/(Sum(Fields!Denominator.Value)+Double.Epsilon),
     nothing)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top