VBA Conditions – Teach Your Program to Think
Conditional statements allow your VBA program to make decisions. They check a condition and run different blocks of code based on whether the condition is True or False. These are used whenever your program needs to choose between multiple paths.
4.1 What are Conditional Statements?
Conditional statements are used when you want your code to behave differently based on given conditions. Example: If marks are 40 or more, student passes. Otherwise, fails.
4.2 Types of Conditional Statements in VBA
- If...Then
- If...Then...Else
- If...ElseIf...Else
- Select Case
4.3 If...Then Statement
This runs code only if the condition is True.
Syntax:
If condition Then
Statement
End If
Example:
Sub IfExample()
Dim age As Integer
age = 20
If age >= 18 Then
MsgBox "You are eligible to vote."
End If
End Sub
Output: You are eligible to vote.
4.4 If...Then...Else Statement
This structure runs one block if the condition is True, otherwise another block runs.
Sub PassFailExample()
Dim marks As Integer
marks = 35
If marks >= 40 Then
MsgBox "Pass"
Else
MsgBox "Fail"
End If
End Sub
Output: Fail
4.5 If...ElseIf...Else Statement
Used when multiple conditions need to be checked one by one.
Sub GradeExample()
Dim marks As Integer
marks = 85
If marks >= 90 Then
MsgBox "Grade A+"
ElseIf marks >= 75 Then
MsgBox "Grade A"
ElseIf marks >= 60 Then
MsgBox "Grade B"
Else
MsgBox "Grade C"
End If
End Sub
Output: Grade A
4.6 Select Case Statement
Select Case is used when there are multiple clear categories or values. It is cleaner and more readable than multiple ElseIf statements.
Syntax:
Select Case expression
Case value1
Statements
Case value2
Statements
End Select
Example:
Sub DayExample()
Dim dayNum As Integer
dayNum = 3
Select Case dayNum
Case 1
MsgBox "Monday"
Case 2
MsgBox "Tuesday"
Case 3
MsgBox "Wednesday"
Case 4
MsgBox "Thursday"
Case 5
MsgBox "Friday"
Case 6
MsgBox "Saturday"
Case 7
MsgBox "Sunday"
Case Else
MsgBox "Invalid Day"
End Select
End Sub
Output: Wednesday
4.7 Real-Life Uses of Conditional Statements
- Check if a student passed or failed
- Calculate discounts based on purchase amount
- Show salary category based on salary range
- Identify weekdays and weekends
- Check login status (successful or failed)
4.8 Practice Exercises
- Write a program to check if a number is positive or negative.
- Write a program to check if a person is eligible for a driving license (age >= 18).
- Write a program to assign grades using If...ElseIf.
- Write a program using Select Case to display the month name (1–12).
- Write a program to check if a number is even or odd.

0 Comments