The VBA CBool Function

Description

The VBA CBool function evaluates an expression, and returns the result as a Boolean data type.

The syntax of the CBool function is:

CBool( Expression )

Where the Expression argument is the expression that that you want to convert to a Boolean.


CBool Expression Types

The CBool function is often used to return the result of a logical expression (see example 1 below). However, the function can also be used to convert numeric values into Boolean data values (see example 2). In this case:

If the supplied Expression is a string that cannot be converted into a Boolean or a Numeric value, the CBool function returns an error.


VBA CBool Function Examples

Example 1

The following VBA code shows how the CBool function can return the result of a logical expression.

' Test if two integers are equal
Dim int1 As Integer
Dim int2 As Integer
Dim int3 As Integer
Dim bool1 As Boolean
Dim bool2 As Boolean
int1 = 1
int2 = 5
int3 = 1
bool1 = CBool( int1 = int2 )
' bool1 is now equal to False
bool2 = CBool( int1 = int3 )
' bool2 is now equal to True

After running the above VBA code, the variable bool1 = False and the variable bool2 = True.


Example 2

The following VBA code shows how the CBool function can convert different data types into Booleans.

' Convert Integer, String and Date values into Booleans
Dim bool1 As Boolean
Dim bool2 As Boolean
Dim bool3 As Boolean
Dim bool4 As Boolean
bool1 = CBool( 0 )
' bool1 is now equal to False
bool2 = CBool( -10.5 )
' bool2 is now equal to True
bool3 = CBool( "5" )
' bool3 is now equal to True
bool4 = CBool( #1/1/2016# )
' bool4 is now equal to True

After running the above VBA code:


VBA CBool Function Error

If you supply the CBool function with a String Expression, that cannot be converted to a number, you will get the error:

Run-time error '13': Type mismatch

VBA Run Time Error 13 Message Box