tech on the net
Home About Us Feedback Site Map

Microsoft

Access Excel Word

Database

SQL Oracle / PLSQL SQL Server MySQL MariaDB PostgreSQL

Web Development

HTML CSS Color Picker

Language

C Language

More

ASCII Table Linux UNIX Java Clipart Joke of the Moment
Share this page:

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

Learn how to use the Excel IF-THEN-ELSE statement (in VBA) with syntax and examples.

Description

The Microsoft Excel IF-THEN-ELSE statement can only be used in VBA code. It returns a value if a specified condition evaluates to TRUE, or another value if it evaluates to FALSE.

Syntax

The syntax for the Microsoft Excel 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

Parameters or Arguments

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

  • If no condition is met, then the Else portion of the IF-THEN-ELSE statement will be executed.
  • It is important to note that the ElseIf and Else portions are optional.

Applies To

The IF-THEN-ELSE statement can be used in the following versions of Microsoft Excel:

  • Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Type of Excel Function

The IF-THEN-ELSE statement can be used in Microsoft Excel as the following type of function:

  • VBA statement (VBA)

Example (as VBA Function)

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

Let's look at some Excel IF-THEN-ELSE statement function examples and explore how to use the IF-THEN-ELSE statement in Excel VBA code:

First, let's look at a simple example.

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

Next, let's 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 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