How to handle IIF or Switch divide by zero giving #ERROR?

久未见 提交于 2019-11-27 09:52:31

The problem with the IIF function is that it is a function not a language construct. This means that it evaluates both parameters before passing the parameters to the function. Consequently, if you have a divide by zero error, this will get evaluated and cause an #ERROR condition even when it looks like that code shouldn't be executed due to boolean condition of the IIF statement.

There are two workarounds for this problem:

IIF bypass

Basically make two IIF function calls where you won't get divide by zero errors:

=IIF(ReportItems!Textbox54.Value <> 0, 
    ReportItems!Textbox56.Value / IIF(ReportItems!Textbox54.Value = 0, 1, ReportItems!Textbox54.Value),
    "N/A")

So where ReportItems!Textbox54.Value is zero, divide by 1 instead, throw that result away and use N/A.

Custom Code

Create a safe divide by zero function in custom code where you can use real language constructs.

Public Function SafeDivide(ByVal Numerator As Decimal, ByVal Denominator As Decimal) As Decimal
    If Denominator = 0 Then
       Return 0
    End If
    Return (Numerator / Denominator)
End Function

and then use this in your report for the Value expression instead of IIF or SWITCH:

=Code.SafeDivide(ReportItems!Textbox56.Value, ReportItems!Textbox54.Value)

and use a Format string to display zeroes as "N/A":

#,##0.00;-#,##0.00;N/A
dzakfi

try the below code

  =IIF(ReportItems!Textbox54.Value = 0,nothing, IIF(ReportItems!Textbox54.Value = 0,1,ReportItems!Textbox56.Value) / IIF(ReportItems!Textbox54.Value = 0,1,ReportItems!Textbox54.Value) )

never zero condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!