Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

vba - Weird behaviour of NOT

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"

Outputs

Post message: True
Hello
There

According to the docs, PostMessage is declared like this:

BOOL PostMessageA(
  HWND   hWnd,
  UINT   Msg,
  WPARAM wParam,
  LPARAM lParam
);

With the comment:

If the function succeeds, the return value is nonzero.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...