The Boolean Data Type

The Boolean data type is a special case of an integer data type. The Boolean data type can contain True or False; internally, Microsoft® Visual Basic® for Applications (VBA) stores the value of True as -1, and the value of False as 0.

You can use the CBool function to convert any numeric value to a Boolean value. When another numeric data type is converted to a Boolean value, any nonzero value is equivalent to True, and zero (0) is equivalent to False. For example, CBool(7) returns True, and CBool(5 + 2 – 7) returns False, because it evaluates to CBool(0).

The following procedure determines whether a number is even. The procedure uses the Mod operator to determine whether a number can be divided by 2 with no remainder. If a number is even, dividing by 2 leaves no remainder; if it is odd, dividing by 2 leaves a remainder of 1:

Function IsEven(lngNum As Long) As Boolean
   ' Determines whether a number is even or odd.
   
   If lngNum Mod 2 = 0 Then
      IsEven = True
   Else
      IsEven = False
   End If
End Function

Another way to write this procedure is to convert the result of an expression to a Boolean value and then use the Not keyword to toggle its value, as shown in the following example. If the lngNum argument is odd, then it must be nonzero; converting lngNum to a Boolean value yields True. Because the procedure must return False if the value is odd, using the Not keyword to toggle the Boolean value gives the correct result.

Function IsEven(lngNum As Long) As Boolean
   ' Determines whether a number is even or odd.
   
   IsEven = Not CBool(lngNum Mod 2)
End Function

Note that the revised IsEven procedure condenses a five-line IfThen statement into a single line of code. If you are using an IfThen statement to set a value to True under one condition and to False under another, as the IsEven procedure does, you can condense the IfThen statement by modifying its condition to return True or False. However, the revised procedure might be somewhat harder to understand.

See Also

Working with Numbers | The Integer, Long, and Byte Data Types | The Floating-Point Data Types | The Currency and Decimal Data Types | Conversion, Rounding, and Truncation | Formatting Numeric Values | Using the Mod Operator | Performing Calculations on Numeric Arrays