VBA Boolean Data Type

- Written by Puneet

excelchamps-free-courses-puneet-gogia

What is a Boolean Data Type?

A boolean data type in VBA allows you to store a Boolean value. There are two Boolean values: TRUE and FALSE. This is a fundamental data type in the VBA that helps you store the result of a logical test where an outcome is always in TRUE or FALSE, flow a statement that works when a certain condition is met, or a pre-defined state where you want to use TRUE or FALSE in the entire code.

How to Declare a Boolean Data Type in VBA

To declare a variable or a constant as a Boolean Data Type, you can use the below-mentioned step:

declare-boolean-data-type
  1. First, you need to enter the “DIM” keyword, which stands for declare. You need to enter it to declare a variable.
  2. After that, enter the name of the variable you want to use. Here, in this example, we have used “myBLN”.
  3. Next, enter the keyword “As” to open the data type list. The moment you type it, you’ll get the drop-down list.
  4. Finally, select the data type from the list or type it from the keyboard.
Sub boolean_data_type()
Dim myBLN As Boolean
End Sub

Once you declare the variable, you can assign a value to it. But that value needs to be a Boolean. Let’s take an example to understand it.

value-needs-to-be-boolean
Sub boolean_data_type()
Dim myBLN As Boolean
myBLN = 2 > 1
Debug.Print myBLN
End Sub

In this example, we have written a condition to test if 2 is greater than 1. This condition is TRUE, and when we run this code to get the result in the immediate window, it has returned TRUE.

But here, instead of getting the result directly, we used a variable with a Boolean data type to store it.

Error with the Boolean Data Type

As we have discussed, the Boolean Data type is designed to store a Boolean value. But if you try to or my mistake, assign a value that is not a Boolean, it will return a Type Mismatch Error.

error-with-boolean-data-type
Sub boolean_data_type()
Dim myBLN As Boolean
myBLN = "Hello"
End Sub

In the above code, we declared the variable as a Boolean, but we used text while assigning a value. When you run this code, it shows an error because our defined value is not a Boolean.

Use Boolean Data Type with a Constant

Like a variable, you can use a Boolean with a constant if you want to use a Boolean value throughout the code and don’t want to change it.

use-boolean-data-type-with-a-constant
Sub boolean_data_type()
Const myBLN As Boolean = True
End Sub

Benefits of using Boolean Data Type

  • If you want to store the result of a condition, the best way is to use the Boolean data type. This helps you to get TRUE or FALSE with their actual value instead of using them as text.
  • It also gives you greater flexibility. Once you declare a variable as Boolean, its value can change the code while running. If a condition is TRUE or FALSE, it can store both values.
Last Updated: April 19, 2024