简体   繁体   中英

VBA What does Cbool mean? (in ACTUAL English)

I can't seem to understand the second line:

 If Not CBool(GetKeyState(vbKeyRButton) And &H8000)

Would you be kind and please explain what this is saying in plain English? All I can understand from this is "If not" and "And" I have strong faith in all the VBA wizards here! Please help me!

The full code is as below:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Not CBool(GetKeyState(vbKeyRButton) And &H8000) Then

    If IsEmpty(strBoardSize) Then
        Exit Sub
    End If
Else
End if
Sub end

strBoardSize is the size of a table and is previously

Dim strBoardSize as string

According to this page , the CBool method takes any input and tries to do a boolean comparison of the value.

So, in English:

If the value returned by (GetKeyState(vbKeyRButton) And &H8000) is not true, then:
   If IsEmpty(strBoardSize) Then
       Exit Sub
   End If
Else
End if

Another way to look at this is:

Dim LCompare as Boolean
LCompare = CBool(GetKeyState(vbKeyRButton) And &H8000) 'Sets the value returned from CBool in LCompare
If Not LCompare Then
   If IsEmpty(strBoardSize) Then
       Exit Sub
   End If
Else
End if

This other article explains what the inputs for GetKeyState are and how they affect the bitwise operators going on.

Hopefully this helps out a bit...

GetKeyState is a Windows API function described at https://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx . It returns an Integer, and as stated, "If the high-order bit is 1, the key is down; otherwise, it is up." (Here, the key of interest is the right mouse button, specified by the constant vbKeyRButton.)

The &H8000 is an Integer with only the high-order bit set, so the And operation returns either 0 or &H8000. &H8000 is a mask (in the vernacular) for the high-order bit.

The CBool function converts 0 to False and any non-zero value to True, so here, it returns True if the key is pressed and False otherwise.

CBool literally means "Convert To Boolean"(It is a cast) because GetKeyState and &H8000 aren't type boolean it needs to be converted or cast.

If Not CBool(GetKeyState(vbKeyRButton) And &H8000)

So for your code it would mean:

If vbKeyRButton AND &H8000 are both false then ...

For the rest of the code,

If IsEmpty(strBoardSize)

This checks if the String strBoardSize is empty. So it's If strBoardSize is empty go to the next line of code, otherwise end the if statement and go on to the else (But you have nothing there)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM