Using If and If-Then structures to make decisions
Of all the control structures in VBA, the If
-Then
and ElseIf
structures are probably the most important. You will use these more than any of the other structures.
The word If sets a condition. It works like normal English; If you do not study, you may fail your exam. In other words, you need to make a decision. If you study, you pass, or else you fail.
In this recipe, we explain this control structure and its conditional statement with two examples, the first being very basic, and the second slightly more complex. Simplistic or not, you will see how you can use code to make your life easier. PCs are much faster than the human brain when it comes to repetitive tasks and decisions.
Getting ready
With ProgramFlow.xlsm
still open on Sheet1, enter the single word Red
in cell A1.
Press Alt + F11 to switch to the VBA Editor. With that active, insert a new module.
How to do it…
There are many ways of using the If...