The Wayback Machine - https://web.archive.org/web/20240926153313/https://www.geeksforgeeks.org/how-to-use-if-statement-in-excel-vba/
Open In App

VBA IF Statement

Last Updated : 12 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 use how to use the If statement in Excel VBA.

Implementation

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

No Developer-button.

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.

Customize-the -Ribbon

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

Check the developer tab

  • Now, the Developer Tab is visible.

Developer-tab

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.

Create-Macro

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

Write-code

VBA IF Statement 

The syntax is :

If condition/expression Then
Code Block for True value

Flow Diagram :

Flow Diagram

Example: Consider a company that wants to hire employees for a certain role. The company kept eligibility criteria as the age of the person. The age of the candidate who can apply for this interview must be less than 27 years.

Sub Allocate_Employee()
‘Declaring and initializing the variable age
Dim age As Integer
age = 30
If age >= 27 Then
MsgBox “You are not eligible for this post.”
End If
End Sub

Output: 

Since, the age is 30, the IF condition becomes TRUE and the code block inside IF statement executes.

Message

Related Topic: Record Macros in Excel

IF Then Statements in Excel

VBA If-Then Statements serve as conditional checks to determine whether expressions are TRUE or FAlse, enabling the execution of different sets of code based on the evaluation.

Let’s delve into a straightforward example to better understand this concept:

If Range(“A2”).Value >0 Then Range(“B2”).Value = “Positive”

In this case, the code tests whether the value within Range A2 is greater than zero. If this condition holds true, the code proceeds to set the value of Range B2 as “Positive”.

Code

Note: When assessing conditions, we employ comparison operators such as =,>,<,<>,<=, and >=. A more detailed exploration of these operators will follow later in this article.

Here’s the syntax for a concise single-line If statement:

If [test_expressions] Then [action]

To enhance readability, you can utilize a line continuation character(underscore) to spread the If statement across two lines, as demonstrated in the image above:

If [test_expression] then_

[action]

If Range(“a2”).Value >0 Then _

Range(“b2”).Value = “Positive”

End If Statements

The previously illustrated “Single-line” If statement effectively addresses scenarios where you are testing a single condition. However, as your IF Statements grow more intricate, involving multiple conditions, it becomes imperative to incorporate an “End If” Statement to delineate the conclusion of the conditional logic.

For example, observe the following code:

If Range(“A2”).Value >0 Then

Range(“B2”).Value = “Positive”

End If

If_Then

Syntax:

If [test_expression] then

[action]

End If

Then End If signifies the end of the if statement.

Using ElseIf with the VBA If Statement -Multiple Conditions

To address more nuanced scenarios involving multiple conditions, the ElseIf and Else Statements become integral components within your VBA code. The ElseIf statement supplements an existing If statement by assessing a condition only if the preceding conditions have not been met.

Consider the following illustration, where we expand upon the initial example of testing for a positive cell value by incorporating an ElseIf condition to determine i the value is negative:

If Range(“A2”).Value>0 Then

Range(“B2″).Value =”Positive”

ElseIf Range(“A2”).Value <0 Then

Range(“B2″).Value =” Negative”

End If

elseif

Multiple ElseIf statements can be employed to accommodate varying conditions, enhancing the decision-making process. Take a look at this code snippet to comprehend its application:

Sub If_Multiple_Conditions()

If Range(“AA2″).Value =”Cat” Then

Range(“B2”).Value = “Kitten”

ElseIf Range (“A2”). Value = “Dog” Then

Range (“A2”).Value = “Puppy”

ElseIf Range (“A2”). Value = “Duck” Then

Range(“B2”).Value = “Duckling”

End If

End Sub

VBA Code

By skillfully integrating ElseIf and Else statements, you adeptly navigate intricate decision paths within your VBA code, enabling you to respond dynamically to diverse scenarios and fostering heightened control and versatility in your Excel projects.

Using Else With the VBA If Statement

For example, the Else statement steps in when neither the positive nor negative conditions hold true, indicating that the cell value must be zero. It serves as a vital catch-all mechanism, ensuring that a definitive outcome is assigned even when other specific conditions are unmet.

By incorporating the Else statement, you bestow your VBA code with the adaptability to handle a comprehensive spectrum of possibilities. Whether it’s dealing with unexpected inputs, exceptional scenarios, or default outcomes, the Else statement empowers your code to gracefully manage diverse circumstances and deliver meaningful results, enhancing the robustness and effectiveness of your Excel applications.

If Range(“a2”). Value>0 Then

Range(“b2”). Value = “Positive”

ElseIf Range(“a2”).Value< 0 Then

Range(“b2”).Value = “Negative”

Else

Range(“b2”).Value = “Zero”

End If

If_Then

Using If-Else Statement in VBA

Among the fundamental constructs of VBA, the If-Else statement stands out as a versatile tool for decision-making within your Excel macros. This construct enables your code to assess conditions and respond dynamically, fostering tailored outcomes based on varying scenarios.

In a basic yet illustrative example, consider the following VBA code:

Sub If_Else()

If Range(“A2”).Value>0 Then

Range (“B2”).Value = “Positive”

Else

Range(“B2”).Value = “Not Positive”

End If

End Sub

If_Else

In this code, the If-Else statements evaluate the value within Rabge A2. If the condition “Range(“A2″). Vaalue>0” holds true, it assigns “positive” to Range B2. Conversely, if the condition is false, it designates “Not Positive” to the same cell.

The If-Else statement embodies the essence of dynamic decision-making, enabling your VBA code to adapt and react based on real-time data. Its significance becomes pronounced as you tackle more intricate tasks, allowing you to handle diverse scenarios, and optimize the workflows, and functionality of your Excel spreadsheets.

By integrating If- Else statements into your VBA toolkit, you empower your macros to make informed choices and deliver relevant outcomes, thereby elevating the precision, efficiency, and intelligence of your Excel projects.

Using Nested IFs Statements

Venturing beyond the confines of basic decision-making, VBA equips you with the capability to construct nested IF statements-empowering your code to explore multiple layers of conditions and responses.

The concept of nested IF statements is exemplified through the following VBA code:

Sub Nested_Ifs()

If Range(“A2”).Value >0 Then

Range(“B2″).Value =”Positive”

Else

If Range(“A2”).Value <0 Then

Range(“B2″).Value =”Negative”

Else

Range(“b2”).Value= “Zero”

End If

End If

End Sub

Nested_Ifs

In this example, a hierarchy of conditions is evaluated. Initially, the code assesses if the value within Range A2 is greater than Zero. Should this condition prove true,” Positive” is assigned to Range B2. In instances where the initial condition is False, the code then delves into a secondary nested IF statement. Here, it checks if the value is less than zero, and if so, assigns “Negative” to Range B2. Should both conditions remain unmet, the final ELSE statement designates “Zero” to the cell.

Nested IF statements grant you the power to navigate intricate decision trees, accommodating various scenarios and delivering precise outcomes. While the example demonstrates a binary hierarchy, you can further expand these constructs to accommodate multiple branches of logic, enhancing the adaptability and intelligence of your Excel macros.

By integrating nested IF statements into your VBA repertoire, you harness a sophisticated mechanism for managing complex conditions and refining the functionality of your Excel projects, contributing to enhanced decision-making and streamlined workflows.

Using Logical Operators with the VBA If Statement

IF-Or, And, Xor, Not

In the realm of VBA, logical operators -Or, And, Xor, and Not -emerge as pivotal tools, fortifying your code with the ability to dissect complex conditions and execute dynamic decisions.

If Or

The Or operator delves into the terrain of inclusivity, assessing whether at least one condition holds True. Observe how the following code scrutinizes a range’s value, gauging if it is less than 5,000 or surpasses 10,000:

If Range(“A2”).Value<5000 Or Range (“A2).Value> 10000 Then

Range(“B2”).Value= “Out of Range”

End If

If Range(“A2”). Value < 5000 or_

Range(“A2”). Value >10000 Or _

Range(“A2”).Value = 9999 Then

Range(“B2”).Value = “Out Of Range”

End If

If And

In contrast, the And operator operates under the premise of totality, evaluating whether ALL conditions converge to true. Consider the ensuring illustration, where the code scrutinizes whether the range value resides within the range of 5,000 and 10,000:

If Range(“A2”). Value >=5000 And Range(“A2”). Value<=10000 Then

Range (“B2”). Value = “In Range”

End If

If Xor

The Xor operator introduces a nuanced perspective, confirming if a singular condition exclusively holds true. Xor returns FALSE when zero conditions or multiple conditions are satisfied.

If Not

If Not is used to convert the False to True or vice versa:

Sub If_Not()

MsgBox Not (True)

End Sub

If_Not

FAQs

What is a VBA If Statements?

An If statement in VBA is a conditional statement that helps you to execute specific code based on whether a given condition is true or False. It forms the core of decision-making in VBA Programming.

How do VBA If statements work?

VBA If statement evaluates a condition and, the code block will execute if the condition is true. And If the condition becomes False, the code block is skipped and the program continues with the next statement after the if block.

What to do if none of the conditions are met in an If statement?

You can use the Else clause to specify a block of code to execute when none of the previous conditions are met.



Similar Reads

VBA Subroutine in Excel - How to Call Sub in VBA?
When a specified action is performed on a worksheet with the help of a collection of code known as a VBA Subroutine. It also helps to read an external file, also it can open other applications from Excel. A large piece of code can be broken into small parts so that we can manage it easily. Let's learn why to use submarines: Converts large piece of
2 min read
How to Use Select Case Statement in Excel VBA?
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 discuss how to use Select Case Statement in Excel VBA. Select Case Statement of Excel VBA The select case i
10 min read
How to use If-Else Statement in Excel VBA?
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 t
2 min read
How to use If-Else-If Statement in Excel VBA?
In this article, we are going to look into how to use the If Else If statement in Excel VBA using a suitable example. 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 th
3 min read
VBA Print Statement in Excel
When there are many columns and rows in excel but we only want to save or print a few of them because that few rows and columns are important to us, at that case we will print them in Excel VBA so that we can fetch those details later and also to get the print out of that table because daily life hard copy of the reports is usually required in the
2 min read
VBA Switch Statement
In Visual Basic for Applications (VBA), when a user needs to execute a series of statements depending on the value of an expression, they turn to the versatile tool known as the "Switch Case." This construct allows programmers to define multiple cases, each representing a different value, and then "switch on" the variable based on these cases. When
5 min read
Excel VBA | count() functions
Visual Basic for Applications (VBA) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA one can automate many tasks in excel and all other office software. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its var
2 min read
How to Use for Each Loop in Excel VBA?
A For Each loop is used to execute a statement or a set of statements for each element in an array or collection. Syntax: For Each element In group [ statements ] [ Exit For ] [ statements ] Next [ element ] The For...Each...Next statement syntax has the following three parts: PartDescriptionelement Required (Must be mentioned). Variable is used to
3 min read
Excel VBA | sum() functions
Visual Basic for Applications (VBA) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA one can automate many tasks in excel and all other office software. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its var
2 min read
Excel VBA | Average() Functions
VBA (Visual Basic for Applications) is the programming language of Excel and other offices. It is an event-driven programming language from Microsoft. With Excel VBA, one can automate many tasks in excel and all other office softwares. It helps in generating reports, preparing various charts, graphs and moreover, it performs calculation using its v
2 min read
How to Declare and Initialize String Array in Excel VBA?
A string array is an array where we can store only string values in the array, with the help of a string array, we can store more than one string value. We can declare the string array in many ways like declaring a static string array, declaring a variant size array of string using the Array function, and a string array using the split function whi
2 min read
Trapping Dynamic Ranges in Excel VBA
Dynamic Ranges give the flexibility to work with more range of cells as compared to a specific range of cells which usually limits us to work with a particular range of cells. As the size of the data may change in an excel sheet so it is also necessary to change the range in the code dynamically for that dynamic ranges are used. We can trap dynamic
3 min read
How to Use the VBA Immediate Window in Excel?
The immediate window is similar to the console in Chrome, where we could execute the javascript. The immediate window allows us to execute macro code very fast and efficiently. Once, you learned it, you will always be found using it. Your immediate window can answer an infinite number of questions, like setting a cell value, changing the sheet of t
5 min read
How to Set Variable to Cell Value in Excel VBA?
Adding data to the worksheet is often done and it is essential to learn how to set variable to cell value in excel VBA. There can be instances when you want to add the same data to your worksheet. This task could easily be achieved with the help of Excel VBA variables. You can assign your cell values with variables. Let's learn how to set variables
5 min read
Excel VBA Concatenation Operators
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. Concatenation means to join two or more data into a single data. There are various ways we can perform concatenation in Excel using built-in
6 min read
Excel VBA Comparison Operators
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. 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? In this a
5 min read
How to use While Wend Loop in Excel VBA?
In this article, we are going to see about While Wend loop in Excel VBA using a suitable example. 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 in the top of the Excel w
2 min read
How to use Do Until Loop in Excel VBA?
In this article, we are going to see look into the Do Until loop in Excel VBA using a suitable example. 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 in the top of the E
3 min read
How to Add a Comment in a VBA in Excel?
VBA Macro is for developers. Macro is a piece of code written in VBA. VBA is Microsoft's programming language and it stands for Visual Basic for Applications. Let's see how to set up our VBA Macro and how to add comments in a VBA in Excel. VBA Macro Excel is a very advanced tool that contains thousands of functionalities, but VBA Macro comes into e
4 min read
How to Use Do While Loop in Excel VBA?
A Do…While loop is used when we want to repeat certain set of statements as long as the condition is true. The condition may be checked at the starting or at the end of the loop Flowchart: Uses of Do-While loop: The Do While loop is used in two ways: Do…while loop which checks the condition at the STARTING of the loop.Do…while loop which checks the
2 min read
How to Use For Next Loop in Excel VBA?
If you are familiar with the programming you must have an idea of what a loop is, In computer programming, a loop is a sequence of statements that are repeated until a specific condition is satisfied. In Excel VBA the "For Next" loop is used to go through a block of code a specific number of times. Syntax: For counter = start to end [step count] [c
4 min read
How to Remove Duplicates From Array Using VBA in Excel?
Excel VBA code to remove duplicates from a given range of cells. In the below data set we have given a list of 15 numbers in “Column A” range A1:A15. Need to remove duplicates and place unique numbers in column B. Sample Data: Cells A1:A15 Final Output: VBA Code to remove duplicates and place into next column (B) Declare Variables: VariablesData Ty
2 min read
How to Find the Last Used Row and Column in Excel VBA?
We use Range.SpecialCells() method in the below VBA Code to find and return details of last used row, column, and cell in a worksheet. Sample Data: Syntax: expression.SpecialCells (Type, Value) Eg: To return the last used cell address in an activesheet. ActiveSheet.Range("A1").SpecialCells(xlCellTypeLastCell).Address VBA Code: Declaring Variables:
2 min read
How to Get Length of Array in Excel VBA?
We use UBound and LBound functions to get the length of an Array in Excel VBA. In this article, we will discuss them in detail. Syntax: UBound() function UBound (arrayname, [ dimension ]) Parameters: arrayname: required. Array variable namedimension: optional Returns: Return upper limit of an array dimension. Syntax: LBound() Function LBound (array
2 min read
How to Create Charts in Excel Using Worksheet Data and VBA?
Excel is an important software provided by Microsoft Corporation. This software belongs to one of the major software suites Office 365. In this software suite, there are other software are present like Word, PowerPoint, etc. They are called Office 365, as this software are mostly used for office purpose. But now the world has changed a lot. After t
6 min read
How to Convert Multiple PowerPoint Files Into Pdf with Excel VBA?
Often clients need PPT files as PDFs. It helps to view on any device. Use below VBA Macro to convert PowerPoint files from a folder and save them as PDF in the same folder. Implementation: Follow the below steps to convert multiple PowerPoint files into PDFs using Excel VBA: Step 1: Open Excel. Step 2: Type text “Folder Path” in cell “B5” (Image 1)
2 min read
How to Delete a Module in Excel VBA?
Have you ever seen a text file in a notepad or a source code file in visual studio code? These all are just basic files where you can write some code or information. Similarly, we have modules in excel, each module has its code window, where you can write some code and allow it to automate your repetitive tasks. There can be multiple modules. We ca
3 min read
How to Run Code from a Module in Excel VBA
VBA Macro is for developers. In Excel, the macro is a piece of code written in VBA and VBA is Microsoft's programming language, it stands for Visual Basic for Applications. The module is a file with a .bcf extension that stores the code written in the Visual Basic for Applications editor. Let's learn, how to run a code from a module in Excel VBA. R
4 min read
MessageBox in Excel VBA
Message Box is one of the most frequently used functions in VBA Macro. The message box is a dialogue box that appears on the screen as an extra window. The dialogue box that appeared asks input from the user and returns a constant/code/number accordingly or it can use to display messages. In this article, we will learn how to create different types
8 min read
Variables and Data Types in VBA Excel
In a computer system, variables and data types are almost used in every program to store and represent data. Similarly, Excel VBA also has variables and data types to store and represent data and its type. In this article, we will learn about VBA variables, their scope, data types, and much more. VBA Variables VBA(Visual Basic for Application) vari
9 min read
Article Tags :