Locked lesson.
About this lesson
Implementing If/Then choices in VBA.
Exercise files
Download this lesson’s related exercise files.
Logic Tests: If Then Else.xlsm28.8 KB Logic Tests: If Then Else - Completed.xlsm
28.1 KB
Quick reference
Logic Tests: If Then Else
Introduction to logic statements
When to use
To create two options for the code to progress, depending on a logical test.
Instructions
VBA If statements allow for branching of results, similar to the IF() function in Excel
VBA If Function Syntax
If <Test> = <Expected Result> Then
<Code to execute if True>
Else
<Code to execute if False>
End If
Or
If <Test> = <Expected Result> Then
<Code to execute if True>
ElseIf <Test2> = <Expected Result 2> Then
<Code to execute if Test2 is True>
Else
<Code to execute if False>
End If
Hints & tips
- The Else section of the code is optional (you are able to test and react to a True result only)
- You can include multiple Else conditions by using the ElseIf <test> structure
Lesson notes are only available for subscribers.