VBA 有三元运算符吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41596121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does VBA Have a Ternary Operator?
提问by soulshined
I come from the beautiful world of Obj C, which is based on the C programming language, and I've fallen in love with finding quirky ways to save space. However, I've looked through as much documentation as I can and I can't find anything juicy on VBA that will shorten this syntax:
我来自 Obj C 的美丽世界,它基于 C 编程语言,我爱上了寻找节省空间的古怪方法。但是,我已经尽可能多地查看了文档,但在 VBA 上找不到任何可以缩短此语法的内容:
If boolVar = True Then
'Do something
Else
'Do nothing
End If
In Obj C, and naturally C, I'm extremely familiar with doing this:
在 Obj C 和自然 C 中,我非常熟悉这样做:
boolVar ? "Nope, tis false" : "Yup, tis true"
This is very similar to what most other languages use, some may use extra logical operators like !=or ==but that leaves me optimistic. I may not have looked in the right places, if that's the case PLEASE let me knowwhere you get your documentation.
这与大多数其他语言使用的非常相似,有些可能使用额外的逻辑运算符,例如!=or==但这让我感到乐观。我可能没有找对地方,如果是这种情况,请告诉我您从哪里获得文档。
TLDR, can we shorten If/Then/Else to one line of code in VBA? This is extremely handywhen the 'Do Somethings' are nothing more then setting another variable's single parameter, or enabling/disabling a button.
TLDR,我们可以在 VBA 中将 If/Then/Else 缩短为一行代码吗?当“做某事”只是设置另一个变量的单个参数或启用/禁用按钮时,这非常方便。
回答by cyboashu
Sub test()
Dim x As Long
Dim y As Long
y = 1
x = IIf(y = 1, 1, 2)
End Sub
回答by user3598756
the closest function is IIf()
最接近的函数是 IIf()
IIf(expr, truepart, falsepart)
but:
但:
you can't have its branches simply running code, while you have to assign its return value to some variable,
it doesn't short-circuit,
it always evaluates both branches so that should one of them fail, even if not the "real" one, the statement would throw an error anyway.
你不能让它的分支简单地运行代码,而你必须将它的返回值分配给某个变量,
它不会短路,
它总是评估两个分支,因此如果其中一个失败,即使不是“真实”的,该语句无论如何都会抛出错误。
So the most resemblingstatement is:
所以最相似的说法是:
If boolVar Then sub1 Else sub2
where:
在哪里:
boolVaris a boolean type variable,sub1andsub2are two different subs/functions to be called.
boolVar是一个布尔类型变量,sub1并且sub2是要调用的两个不同的子/函数。
回答by Jose Natali
As an alternative you can create the following public function in a module:
作为替代方案,您可以在模块中创建以下公共函数:
Public Function iff(expr, trueR, falseR) As Variant
If expr Then iff = trueR Else iff = falseR
End Function
So far works for me.
到目前为止对我有用。

