How to use If…Then…Else statement in VBA?

Using an If…Then…Else statement in VBA (Visual Basic for Applications) is a fundamental way to control the flow of a program based on certain conditions. Here’s a basic structure and an example to illustrate how it works:

Basic Structure

If [condition] Then
    ' Code to execute if condition is True
    ' Code to execute if condition is False
End If
  • [condition]: This is where you put your logical test. If the condition evaluates to True, the first block of code will run; otherwise, the Else block will run.
  • Then: Indicates the start of the block of code that executes if the condition is True.
  • Else (optional): Starts the block of code that executes if the condition is False.
  • End If: Marks the end of the If statement.
Sub CheckAge()
    Dim age As Integer
    age = 25

    If age >= 18 Then
        MsgBox "You are an adult."
        MsgBox "You are not an adult."
    End If
End Sub

In this example:

  • We first declare a variable age and assign it a value of 25.
  • The If statement checks if age is greater than or equal to 18.
  • If the condition is True (which it is in this case), a message box saying “You are an adult.” will appear.
  • If the condition were False, a different message box saying “You are not an adult.” would appear.
  • This is a simple demonstration, but If…Then…Else statements can be more complex, including multiple conditions using ElseIf, or nested If statements for more intricate logic.

Switch the language


Unlock Your Potential


Basic - Advanced


Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project

Leave a Reply

Your email address will not be published. Required fields are marked *