VBA中布尔if语句的奇怪行为 [英] Odd behavior with boolean if statement in VBA

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

问题描述

我编写了一个 if 语句,如下所示:

I coded an if statement as seen below:

您可以在此处看到我将鼠标悬停在此语句中的所有三个值上,并且所有这些值都应与 True 值等效,因此应运行 if 语句中的内容.但是,由于某种原因,当我执行此语句时,它直接跳到代码的 End If 部分.

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 中,AndOr 运算符是按位的,而不是逻辑的.它们对数值操作数进行按位运算,最后才在逻辑上下文中考虑位运算的结果.

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.

在您的示例中,您有 True AND 13 AND 18,即 -1 AND 13 AND 18(在 VB 中 True 等于 -1),结果为 0,因为数字 1318 没有任何公共位.零最终在逻辑上下文中被隐式理解为 False.

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.

通常,当您编写诸如 If Len(str) Then 而不是 If Len(str) > 之类的东西时,您会侥幸逃脱.0 然后 - 因为没有 AndOr 来弄乱结果.
如果条件中确实有它们,则应始终使用显式比较.然后按位运算符将有要操作的布尔操作数,在这种情况下,它们的工作结果将与逻辑运算符相同.
真正的逻辑运算符,AndAlsoOrElse,仅在 VB.NET 中引入.如果您可以将 And 替换为 AndAlso,条件将评估为 True(使用 Option Strict Off,因为使用 Option Strict On 编译器会让你使用显式比较).

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).

注意 Null 与它无关.在 VB 中,逻辑上下文中有 Null 是可以接受的: If Null Then ... Else... 是一个有效的结构.Null 在这种情况下的计算结果为 False.

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中布尔if语句的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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