top of page

You are learning Macros in MS Excel

How to use conditional statements (if/then/else) in VBA code?

VBA offers conditional statements using the `If...Then...Else` structure, similar to other programming languages. Here's how you can use them:

Basic Syntax:

```vba
If condition Then
' Code to execute if the condition is True
Else
' Code to execute if the condition is False
End If
```

Explanation:

- `If condition Then`: This line starts the conditional statement. The `condition` is a logical expression that evaluates to either `True` or `False`.
- `Code to execute...`: These lines contain the statements that will be run if the `condition` evaluates to `True` (for the `Then` block) or `False` (for the `Else` block). You can indent these lines for better readability.
- `End If`: This line marks the end of the conditional statement.

Example:

```vba
Sub CheckAge(age As Integer)

If age >= 18 Then
MsgBox "You are eligible to vote."
Else
MsgBox "You are not eligible to vote."
End If

End Sub
```

Adding Else If:

You can add `ElseIf` statements to check for additional conditions after the initial `If` statement is evaluated as `False`. The syntax follows the same pattern:

```vba
If condition1 Then
' Code to execute if condition1 is True
ElseIf condition2 Then
' Code to execute if condition1 is False and condition2 is True
Else
' Code to execute if all conditions are False
End If
```

Example:

```vba
Sub CheckGrade(score As Integer)

If score >= 90 Then
MsgBox "Excellent!"
ElseIf score >= 80 Then
MsgBox "Great job!"
Else
MsgBox "Keep studying!"
End If

End Sub
```

Tips:

- Use clear and concise variable names for your conditions.
- You can nest `If` statements within other `If` or `ElseIf` blocks for more complex logic.
- Indentation helps improve readability of your code.

By effectively using conditional statements, you can add decision-making capabilities to your VBA code, making it more versatile and powerful.

bottom of page