Search code examples
vbams-accessms-access-2016

Calling an Access VBA function with IF statement as an argument


Assuming I have the following MS Access 2016 function:

Public Function TestFunction(ByVal strTest As String) As String

Is there a way to call the function with something similar to:

strReturn = TestFunction(If a = 1 Then "Apple" Else "Orange")

I would like to write something as compact as possible, and avoid having to write multiple lines for the call, such as:

If a = 1 Then strArg = "Apple" Else strArg = Orange
strReturn = TestFunction(strArg)

Solution

  • You can accomplish this using IIf, e.g.:

    strReturn = TestFunction(IIf(a=1,"Apple","Orange"))
    

    But this is generally discouraged when working with expressions other than constants, because IIf will always evaluate both the then and else argument before returning the appropriate value depending on the outcome of the test expression, which can sometimes lead to undesired results.

    For example, evaluating the following expression at the Immediate Window (Ctrl+G) will result in a division by zero error, even though the else expression will never be returned:

    ?iif(true,"Apple",1/0)