Conditional Statement in VBA

A conditional statement in VBA is used to determine the execution flow. It evaluates one or more conditions and, based on the result, executes specific sections of code. 

The main Excel VBA conditional statements are the If … Then statement and the Select Case statement. 

Conditional statements are useful in programming because they allow you to perform comparisons to decide or loop through certain number of iterations based on a criteria.

In VBA, you can use the If…Then…Else statement to run a specific statement or a block of statements, depending on the value of a condition. Here’s an example of how to use the If…Then…Else statement in VBA:

Sub Example_If ()
    Dim x As Integer
    x = 8
    If x > 6 Then
        MsgBox "x is greater than 6"
    Else
        MsgBox "x is less than or equal to 6"
    End If
End Sub

In this example, if the value of x is greater than 6, the message box will display “x is greater than 6”. Otherwise, it will display “x is less than or equal to 6”.

You can also use the Select Case statement to run one of several blocks of statements, depending on the value of an expression. Here’s an example of how to use the Select Case statement in VBA:

Sub Example_case ()
    Dim x As Integer
    x = 3
    Select Case x
        Case 1
            MsgBox "x is 1"
        Case 2
            MsgBox "x is 2"
        Case 3
            MsgBox "x is 3"

        Case Else
            MsgBox "x is not 1 or 2 or 3"
    End Select
End Sub

If Then Statement

In VBA, you can use the If…Then…Else statement to run a specific statement or a block of statements, depending on the value of a condition.

ElseIf Then Statement

In VBA, you can use the If…Then…Else statement to run a specific statement or a block of statements, depending on the value of a condition.

Case Statement

You can also use the Select Case statement to run one of several blocks of statements, depending on the value of an expression.

Case Is Statement

The CASE statement is a built-in function in Excel that is categorized as a Logical Function.

Scroll to Top