Sample Header Ad - 728x90

VBA IIf Function different result to If Then Else

1 vote
1 answer
57 views
The user-defined function Excel VBA Office 365 Mac (Version 16.86 (24051422)) on macOS Ventura 13.6.7 generates different results if an "IIf" function is used instead of an "If Then Else" statement. Examples follow:
Function myMOD3(a As Double, b As Double) As Variant
 `   myMOD3 = IIf(b = 0, "NaN", a - b * (a \ b))
    myMOD3 = IIf((b  0), (a - b * (a \ b)), ("NaN"))
End Function

Function myMOD4(a As Double, b As Double) As Variant
    If b = 0 Then
        myMOD4 = "NaN"
    Else
        myMOD4 = a - b * (a \ b)
    End If
End Function
The first function, myMOD3 works. However, when "b" is equal to 0, it generates a divide by zero error if called from a Sub in VBA or **"#VALUE!"** when called from Excel. For some reason, the "IIf" does not capture **b=0** or **b0** (the commented-out code has the same result) resulting in the return of "NaN". The second function, myMOD4, also works fine. When b=0, it responds correctly by returning "NaN". Both these functions should produce identical results. Is this just a strange quirk of MS VBA? In other situations, the IIf function appears to work as expected. Does anyone have any ideas?
Asked by Andrew Duncan (29 rep)
May 21, 2024, 01:25 AM
Last activity: Oct 18, 2024, 06:07 AM