Dear John, How Do I... Work with True/False Data?

The Boolean data type stores either the value True or the value False and nothing else. Typically, Boolean variables are used to store the results of comparisons or other logical tests. For example, the following procedure assigns the result of a logical comparison of two values to a Boolean variable named blnTestResult and then prints this variable to the display:

Private Sub Form_Click()
    Dim blnTestResult As Boolean
    blnTestResult = 123 < 246
    Print blnTestResult
End Sub

Notice that the displayed result appears as True in this case. When you print or display a Boolean variable, you print or display either True or False.

WARNING

Watch out for strange variable type coercions! Read onDear John, How Do I...

Visual Basic supports many types of automatic variable type coercions, which means you can assign just about anything to just about anything. For example, even though Boolean variables hold only the values True and False, you can assign a number or even a string to a Boolean variable. The results might not be what you'd expect, though, so be careful!

Here's one short example of this rather strange behavior. The following code will display True, True, and False, which implies that bytA equals True and intB equals True but that bytA does not equal intB! The reason for the final result of False might not be obvious; it results from the internal conversions of the unlike variables bytA and intB to like data types during the test to see whether they equal each other.

Private Sub Form_Click()
    Dim bytA As Byte
    Dim intB As Integer
    bytA = True
    intB = True
    Print bytA = True
    Print intB = True
    Print bytA = intB
End Sub

Use the operators And, Or, and Not to perform logical operations with Booleans. Logical operations combine several conditions in a single statement, creating a result that is either True or False. For example:

If blnExit And Not blnChanged Then End

This line of code ends a program if blnExit is True and blnChanged is False. You can use mathematical operators for the same task, but the logical operators make the code shorter and more readable. By using Boolean variables exclusively in these tests, you also avoid unexpected type coercion.