Trying to use IIF as ternary operator/without evaluating both sides

后端 未结 1 1659
我寻月下人不归
我寻月下人不归 2021-01-21 05:56

I need to use iif() for my case of checking and assigning values like:

Range(\"A1\").Value = IIf(IsNull(Range(\"A2\").Value), MsgBox(\"1\"), MsgBox(         


        
相关标签:
1条回答
  • 2021-01-21 06:04

    The VBA documentation for IIf states that it executes both True and False conditions regardless of its output.

    You need code similar to the following:

    Dim Result as Integer
    If IsNull(Range("A2").Value) Then
        Result = MsgBox("1")
    Else
        Result = MsgBox("2")
    End If
    Range("A1").Value = Result
    

    Alternatively, if you're looking for an one-liner:

    Range("A1").Value = MsgBox(IIf(IsNull(Range("A2").Value), "1", "2"))
    

    Though this doesn't allow you to change the other MsgBox parameters as easily as the block-If.

    0 讨论(0)
提交回复
热议问题