tech on the net

MS Excel: IF-THEN-ELSE Statement (VBA)

In Microsoft Excel, the IF-THEN-ELSE statement can only be used in VBA code.

Syntax

The syntax for the IF-THEN-ELSE statement is:

If condition_1 Then
   result_1

ElseIf condition_2 Then
  result_2
  
...
            
ElseIf condition_n Then
   result_n

Else
   result_else

End If

condition_1 to condition_n are evaluated in the order listed. Once a condition is found to be true, the IF-THEN-ELSE statement will execute the corresponding code and not evaluate the conditions any further.

result_1 to result_n is the code that is executed once a condition is found to be true.

Note

Applies To

Type of Function

VBA Statement Example

The IF-THEN-ELSE statement can only be used in VBA code.

First, let's take a look at a simple example.

If LRegion ="N" Then
   LRegionName = "North"
End If

Next, let's take a look at an example that uses ElseIf.

If LRegion ="N" Then
   LRegionName = "North"

ElseIf LRegion = "S" Then
   LRegionName = "South"

ElseIf LRegion = "E" Then
   LRegionName = "East"

ElseIf LRegion = "W" Then
   LRegionName = "West"
   
End If

Finally, let's take a look at an example that uses Else.

If LRegion ="N" Then
   LRegionName = "North"

ElseIf LRegion = "S" Then
   LRegionName = "South"

ElseIf LRegion = "E" Then
   LRegionName = "East"

Else
   LRegionName = "West"

End If