尝试使用IIF作为三进制操作符,而不评估双方 [英] Trying to use IIF as ternary operator/without evaluating both sides

查看:99
本文介绍了尝试使用IIF作为三进制操作符,而不评估双方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 iif()来检查和分配值,如:

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

我真的很困惑:这行正在执行 MsgBox ES。我需要执行其中一个,取决于条件是否为真。



我尝试使用如果条件,但它会导致错误:编译错误:预期:表达式



请帮助。谢谢。

解决方案

IIf的VBA文档表示它执行True和False条件,无论其输出。



您需要类似以下代码:

  Dim Result as Integer 
如果IsNull(Range(A2 )$ V


$ b结果= MsgBox(2)
结束如果
范围(A1) .Value = Result

或者,如果您正在寻找单行:

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

虽然这不允许您更改其他 MsgBox 参数像块一样容易 - 如果。


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("2"))

I'm really confused with this: the line is executing both MsgBoxes. I need to execute only one of them depending on whether the condition is true/false.

I tried using if condition, but it causes an error: "Compile error: Expected: expression"

Please help. Thanks.

解决方案

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.

这篇关于尝试使用IIF作为三进制操作符,而不评估双方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆