与布尔古怪的行为如果VBA语句 [英] Odd behavior with boolean if statement in VBA

查看:119
本文介绍了与布尔古怪的行为如果VBA语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I codeD的,如果如下所示的语句:

I coded an if statement as seen below:

您可以在这里看到,我徘徊在所有三个值中的这句话和所有的人都应该是一个真正的价值相等,因此里面的内容if语句应该运行。然而,由于某些原因,当我执行该语句,它跳过直接到结束如果的code的一部分。

You can see here that I hovered over all three values in this statement and all of them should be the equivalent of a True value and thus the contents inside the if statement should run. However, for some reason when I execute this statement, it skips straight to the End If part of the code.

有谁知道为什么只要看一眼呢?

Does anyone know why just by looking at this?

推荐答案

在VB中,或者运营商正在按位,不符合逻辑。他们上的数字操作数执行按位运算,只有在年底的位操作的结果可能会在合理的范围内加以考虑。

In VB, the And and Or operators are bitwise, not logical. They perform bitwise operation on the numeric operands, and only in the end the result of the bit operation may be considered in the logical context.

在你的榜样,你有真和13 18 ,这是 -1和13 18 (在VB 等于 1 ),这将导致 0 ,因为数字 13 18 没有任何共同的位。零点到底隐含理解为在逻辑方面。

In your example, you have True AND 13 AND 18, which is -1 AND 13 AND 18 (in VB True equals -1), which results in 0, because numbers 13 and 18 do not have any common bits. The zero is in the end implicitly understood as False in the logical context.

通常你摆脱它,当你写的东西像如果LEN(STR)然后而不是如果LEN(STR)&GT; 0,那么 - 因为没有或者来搞乱结果< BR>
如果你有他们在的情况下,你应该总是使用显式比较。然后按位运算符将具有布尔操作数进行操作,在这种情况下,就好像它们是逻辑操作符他们的工作的结果将是相同的。结果,
真正的逻辑运算符, AndAlso运算 和< A HREF =htt​​p://msdn.microsoft.com/en-us/library/ea1sssb2.aspx> OrElse运算 ,在VB中只介绍了。净。如果你可以用 AndAlso运算取代你的取值 S,条件将评估为(与选项严格关闭,因为选项严格编译器会让你使用显式比较)。

Normally you get away with it when you write things like If Len(str) Then instead of If Len(str) > 0 Then - because there are no And or Or to mess up the result.
If you do have them in the condition, you should always use the explicit comparison. Then the bitwise operators will have boolean operands to operate on, in which case the result of their work will be the same as if they were logical operators.
True logical operators, AndAlso and OrElse, were only introduced in VB.NET. If you could replace your Ands with AndAlsos, the condition would evaluate to True (with Option Strict Off, because with Option Strict On the compiler would make you to use explicit comparison).

注意无关,用它做。这是在VB中可以接受的在逻辑方面:如果null,则......否则...... 是一个有效的结构。 在这种情况下,计算结果为

Note that Null has nothing to do with it. It is acceptable in VB to have Null in the logical context: If Null Then ... Else... is a valid construct. Null in this case evaluates to False.

这篇关于与布尔古怪的行为如果VBA语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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