VBA - Change IF Statements for Reference Table

If Statements are a crucial part of the daily VBA Development process. You can't live without conditional statements since they are, in core, the most fundamental decision derivative expression of programming. However, in Excel, where you have to deal with a lot of conditions, it might get tricky to use them.

Imagine having 7 different conditions and for each condition 2 sub-conditions where 3 of them don't result in final "ELSE" condition. Hard to see, right? How many lines do you need to code to accomplish this? How about if in the future, you need to add more conditions, will you know where to place them?

A lot of If Statements can be replaced for a table that drives all possible conditions. This will help with readability and will also help you to avoid modifying or adding more code in the future.

Check this example where you have to return a fruit type based on the arguments passed to a function. (DO NOT PAY ATTENTION TO DESCRIPTIONS, THEY ARE VERY RANDOM SELECTED).



Doesn't this look nasty? Yes, we just tried with a couple of fruit and this went out of control. Imagine having a full list with hundreds of fruits and subconditions for each fruit that you need to update every month. CRAZY! In cases like this, you need to avoid if statements and use a reference table instead. Check how easy and organized is the following schema table:





And use the following Code to filter out and return Type from the Table:



I put some comments in the code for you to better understand the procedure but the main point I want to give here it's to use Reference Table to substitute big, nested if statements. It's easy to maintain, more legible and readable and more escalable.


That's all folks!
Cheers,

Comments

Popular posts from this blog

VBA - Using JSON in VBA

VBA - Copy Sheet from One Workbook to Another