Open In App
Related Articles

How to use If-Else Statement in Excel VBA?

Improve Article
Save Article
Like Article

VBA in Excel stands for Visual Basic for Applications which is Microsoft’s programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend.

In this article, we are going to learn how to use the  If Else statement in Excel VBA.

Implementation :

In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. 

The Developer Tab can be enabled easily by a two-step process :

  • Right-click on any of the existing tabs at the top of the Excel window.
  • Now select Customize the Ribbon from the pop-down menu.

  • In the Excel Options Box, check the box Developer to enable it and click on OK.

  • Now, the Developer Tab is visible.

Now click on the Visual Basic option in the Developer tab and make a new module to write the program using the Select Case statement.

Developer  -> Visual Basic -> Tools -> Macros
  • Now create a Macro and give any suitable name.

  • This will open the Editor window where can write the code.

IF Statement :

The syntax for the If-Else statement in Excel is :

If condition/expression Then
Code Block for True
   Code Block for False
End If

Flow Diagram :

Example: Suppose a company kept a new policy. Due to COVID-19. The policy is odd and even days physical presence in the office. The employees whose age is an even number will work on Monday and Wednesday and the employees whose age is odd will work on Tuesday and Thursday.

Sub Allocate_Employee()
'Declaring the variable age
Dim age As Integer
'Asking age from the employee
age = InputBox("Please enter your age:")
If (age Mod 2) = 0 Then
 MsgBox "You have to visit office on Monday and Wednesday"
  MsgBox "You have to visit office Tuesday and Thursday"
End If
End Sub

Output 1: If the user enters 24 which will be an even number will result in a TRUE value in IF. So, the block of code inside IF will only work.

Enter Age and Click OK


Output 2: If the user enters 27 which will be an odd number will result in a FALSE value in IF. So, the block of code inside Else will only work.

Some helpful links to get more insights about Macros, VBA in Excel :

  1. Record Macros in Excel.
  2. How to Create a Macro in Excel?
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 19 Jul, 2021
Like Article
Save Article
Similar Reads
Complete Tutorials