VBA – Easy Way to Handle TRUE/FALSE Tests

Using a boolean variable

Let’s say you have VBA code that handles a budget and a forecast. There is a cell B2 on the Input sheet that contains the word Budget or Forecast. Based on that cell the macro with do different things. You may need to test for Budget/Forecast a few times within the code. There is an easy and flexible way to handle this.

The code below (which is an image) will help demonstrate this technique

Boolean

 

  1. Define your variables – always define your variables. Boolean means TRUE or FALSE. I use the prefix boo for Boolean. Some people use b or no prefixes at all. I like to use a standard prefix so that I know what type of data the variable should contain. If you don’t use a prefix you have to keep checking the Dim statements at the top to see the type of the variable. Apparently this is old school, but hey, I am old school.
  2. Capture whether cell B2 contains Budget. By comparing the cell to Budget you return TRUE if it is Budget or FALSE if it is anything else. I have enclosed the comparison in brackets to make it obvious what is happening. Having two equal signs within a formula can be confusing.
  3. Now whenever I need to know if Budget was selected I can use this short If statement. I can use this same If statement throughout the code whenever I need to do something differently between the budget and the forecast.
  4. You can do all the budget processes here.
  5. All the forecast processes here.
  6. I have used a msgbox to check if the code is working correctly.
  7. Always set your object variables to Nothing at the end of your code. This frees up memory. Object variables are coloured black in the Dim statement.

The beauty of this technique is that you are only checking the cell once. Every time you interact with the sheet it slows the macro down. Also, if you have multiple checks throughout your code then centralising the check into one variable at the start means it is easy to change if, for example, the cell reference changes.

In this case I would advise using a range name for the cell, and using that range name in the code.

Download the example file below.

TRUE_FALSE

Please note: I reserve the right to delete comments that are offensive or off-topic.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.