问题描述
我正在遇到一些布尔变量的怪异行为;以下代码同时显示"Hello"和"There",表示result
& NOT result
均评估为True
I'm experiencing some weird behaviour of boolean variables; the following code prints both "Hello" and "There", meaning result
& NOT result
both evaluate to True
Dim result As Boolean
result = PostMessage(Application.hWnd, 275, 0, 0)
Debug.Print "Post message: "; result
If result Then Debug.Print "Hello"
If Not result Then Debug.Print "There"
输出
Post message: True
Hello
There
根据文档, PostMessage 的声明如下:
According to the docs, PostMessage is declared like this:
BOOL PostMessageA(
HWND hWnd,
UINT Msg,
WPARAM wParam,
LPARAM lParam
);
带有评论:
这是我在VBA中的使用方式:
Here's how I have it in VBA:
Public Declare Function PostMessage Lib "user32" Alias "PostMessageA" ( _
ByVal hWnd As LongPtr, _
ByVal msg As Long, _
ByVal wParam As LongPtr, _
ByVal lParam As LongPtr) As Boolean
那是什么导致怪异的行为呢?我该如何解决?
So what's causing the weird behaviour? How do I get around it?
推荐答案
尽管通常 VBA Boolean
可以容纳True
(-1
)或False
(0
) ,可能会有些诡异地在此类型中插入另一个值.
Although normally a VBA Boolean
holds either True
(-1
) or False
(0
), it is possible to insert another value into this type with some trickery.
这就是这里发生的情况:您错误指定的API调用返回的整数类型的值既不是-1
也不是0
.
This is what is happening here: your mis-specified API call is returning an integral type with a value that's neither -1
nor 0
.
由于NOT(a)
是0
,并且仅当a
是-1
时,如果Boolean
中的有效载荷不是-1
或-1
,则将同时打印Hello
和There
. 0
.
Since NOT(a)
is 0
if and only if a
is -1
, both Hello
and There
will be printed if the payload in the Boolean
is anything other than -1
or 0
.
这篇关于NOT的怪异行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!