Search
Close this search box.

VBA Nested If Statement


Nested If...Then...Else statements allow you to create complex decision-making structures within your VBA code. This enables you to evaluate multiple conditions and execute different code blocks based on the outcome of those conditions.

Syntax:

If condition1 Then
‘ Code to execute if condition1 is True
If condition2 Then
‘ Code to execute if both condition1 and condition2 are True
Else
‘ Code to execute if condition1 is True but condition2 is 1 False
End If
Else
‘ Code to execute if condition1 is False
End If

Example

				
					Sub CheckNumber()
    Dim number As Integer
    number = -10

    If number > 0 Then
        MsgBox "The number is positive"
    Else
        If number < 0 Then
            MsgBox "The number is negative"
        Else
            MsgBox "The number is zero"
        End If
    End If
End Sub
				
			

Explanation:

  1. The outer If condition checks if number is greater than 0.
  2. If number is greater than 0, the inner If condition is not executed, and the message “The number is positive” is displayed.
  3. If number is not greater than 0, the Else block is executed.
  4. Within the Else block, another If condition checks if number is less than 0.
  5. If number is less than 0, the message “The number is negative” is displayed.
  6. If number is neither greater than 0 nor less than 0, it must be 0, so the message “The number is zero” is displayed.

Key Points:

  • You can nest multiple levels of If...Then...Else statements to create complex decision-making structures.
  • Indentation is crucial for readability and understanding the nesting levels.
  • Use comments to explain the logic of your code, especially for complex nested structures.
  • Consider using Select Case statements for multiple comparisons based on a single variable.