Содержание
- Заявление VBA If
- ElseIF — несколько условий
- Еще
- Если еще
- Вложенные IF
- ЕСЛИ — Или, И, Xor, Не
- Если сравнения
- Если петли
- Если остальные примеры
- VBA If, ElseIf, Else в Access VBA
Если то
Операторы If в VBA позволяют проверять, являются ли выражения ИСТИННЫМИ или ЛОЖНЫМИ, выполняя другой код в зависимости от результатов.Давайте посмотрим на простой пример:
1 | Если Range («a2»). Value> 0, то Range («b2»). Value = «Positive» |
Это проверяет, больше ли значение в диапазоне A2, чем 0. Если да, установите для диапазона B2 значение «Положительный».Примечание: при тестировании условий мы будем использовать операторы сравнения =,>, <,, =. Подробнее о них мы поговорим позже в статье.Вот синтаксис простого однострочного оператора If:
1 | Если [test_expression], то [действие] |
Чтобы упростить чтение, вы можете использовать символ продолжения строки (подчеркивание), чтобы расширить операторы If до двух строк (как мы это сделали на рисунке выше):
12 | Если [test_expression], то _[действие] |
12 | Если Range («a2»). Value> 0 Then _Диапазон («b2»). Значение = «Положительное» |
Конец, если
Приведенный выше «однострочный» оператор if хорошо работает, когда вы проверяете одно условие. Но по мере того, как ваши операторы IF усложняются с несколькими условиями, вам нужно будет добавить «End If» в конец оператора if:
123 | Если Range («a2»). Value> 0, тоДиапазон («b2»). Значение = «Положительное»Конец, если |
Вот синтаксис:
123 | Если [test_expression], то[действие]Конец, если |
End If означает конец оператора if.
Теперь давайте добавим ElseIF:
ElseIF — несколько условий
ElseIf добавляется к существующему оператору If. ElseIf проверяет выполнение условия ТОЛЬКО если предыдущие условия не были выполнены.В предыдущем примере мы проверили, положительное ли значение ячейки. Теперь мы также проверим, является ли значение ячейки отрицательным с помощью ElseIf:
12345 | Если Range («a2»). Value> 0, тоДиапазон («b2»). Значение = «Положительное»ElseIf Range («a2»). Значение <0 ТогдаДиапазон («b2»). Значение = «Отрицательное»Конец, если |
Вы можете использовать несколько ElseIf для проверки нескольких условий:
1234567891011 | Sub If_Multiple_Conditions ()Если Range («a2»). Value = «Cat», тоДиапазон («b2»). Значение = «Мяу»ElseIf Range («a2»). Value = «Dog» ТогдаДиапазон («b2»). Значение = «Гав»ElseIf Range («a2»). Value = «Duck» ТогдаДиапазон («b2»). Значение = «Кряк»Конец, еслиКонец подписки |
Теперь мы добавим Еще:
Еще
В Еще будет работать, если никакие другие предыдущие условия не были выполнены.
Мы закончим наш пример, используя Else, чтобы указать, что если значение ячейки не является положительным или отрицательным, то оно должно быть равно нулю:
1234567 | Если Range («a2»). Value> 0, тоДиапазон («b2»). Значение = «Положительное»ElseIf Range («a2»). Значение <0 ТогдаДиапазон («b2»). Значение = «Отрицательное»ЕщеДиапазон («b2»). Значение = «Ноль»Конец, если |
Если еще
Самый распространенный тип оператора If — это простой If-Else:
1234567 | Sub If_Else ()Если Range («a2»). Value> 0, тоДиапазон («b2»). Значение = «Положительное»ЕщеДиапазон («b2»). Значение = «Не положительное»Конец, еслиКонец подписки |
Вложенные IF
Вы также можете «вкладывать» операторы if друг в друга.
1234567891011 | Sub Nested_Ifs ()Если Range («a2»). Value> 0, тоДиапазон («b2»). Значение = «Положительное»ЕщеЕсли Range («a2»). Value <0 ThenДиапазон («b2»). Значение = «Отрицательное»ЕщеДиапазон («b2»). Значение = «Ноль»Конец, еслиКонец, еслиКонец подписки |
ЕСЛИ — Или, И, Xor, Не
Далее мы обсудим логические операторы: Or, And, Xor, Not.
Я для
В Или оператор проверяет, если как минимум одно условие выполнено.
Следующий код проверяет, является ли значение в диапазоне A2 меньше 5000 или больше 10000:
123 | Если Диапазон («a2»). Значение 10000 ТогдаДиапазон («b2»). Значение = «Вне диапазона»Конец, если |
Вы можете включить несколько Ор в одну строку:
123 | Если Диапазон («a2»). Значение 10000 Или Диапазон («a2»). Значение = 9999 ТогдаДиапазон («b2»). Значение = «Вне диапазона»Конец, если |
Если вы собираетесь использовать несколько OR, рекомендуется использовать символ продолжения строки, чтобы облегчить чтение кода:
123456 | Если Диапазон («a2»). Значение <5000 или _Диапазон («a2»). Значение> 10000 или _Диапазон («a2»). Значение = 9999 ТогдаДиапазон («b2»). Значение = «Вне диапазона»Конец, если |
Если и
Оператор And позволяет проверить, ВСЕ условия соблюдены.
123 | Если Range («a2»). Value> = 5000 And Range («a2»). Value <= 10000 ThenДиапазон («b2»). Значение = «В диапазоне»Конец, если |
Если Xor
Оператор Xor позволяет проверить, выполняется ровно одно условие. Если соблюдаются нулевые условия, Xor вернет FALSE, если два или более условий выполнены, Xor также вернет false.
Я редко видел, чтобы Xor использовался в программировании на VBA.
Если не
Оператор Not используется для преобразования FALSE в TRUE или TRUE в FALSE:
123 | Sub IF_Not ()MsgBox Not (True)Конец подписки |
Обратите внимание, что для переключения оператора Not требуется скобка, заключающая выражение.
Оператор Not также может применяться к операторам If:
123 | Если нет (Диапазон («a2»). Значение> = 5000 и диапазон («a2»). Значение <= 10000), тоДиапазон («b2»). Значение = «Вне диапазона»Конец, если |
Если сравнения
При сравнении обычно используется один из операторов сравнения:
Оператор сравнения | Объяснение |
---|---|
= | Равно |
Не равно | |
> | Больше чем |
>= | Больше или равно |
< | Меньше, чем |
<= | Меньше или равно |
Однако вы также можете использовать любое выражение или функция что приводит к ИСТИНА или ЛОЖЬ
Если — логическая функция
При построении выражений для операторов If вы также можете использовать любую функцию, которая генерирует TRUE или False. VBA имеет несколько из этих функций:
Функция | Описание |
---|---|
IsDate | Возвращает ИСТИНА, если выражение является допустимой датой. |
Пустой | Проверьте наличие пустых ячеек или неопределенных переменных |
IsError | Проверить значения ошибок |
Нулевой | Проверить значение NULL |
IsNumeric | Проверить числовое значение |
Их можно назвать так:
1 | Если IsEmpty (Range («A1»). Value), то MsgBox «Cell Empty» |
В Excel также есть много дополнительных функций, которые можно вызывать с помощью WorksheetFunction. Вот пример функции Excel IsText:
12 | Если Application.WorksheetFunction.IsText (Range («a2»). Value), то _MsgBox «Ячейка — это текст» |
Вы также можете создавать свои собственные определяемые пользователем функции (UDF). Ниже мы создадим простую логическую функцию, возвращающую ИСТИНА. Затем мы вызовем эту функцию в нашем операторе If:
1234567891011 | Sub If_Function ()Если TrueFunction, тоMsgBox «True»Конец, еслиКонец подпискиФункция TrueFunction () как логическое значениеTrueFunction = TrueКонечная функция |
Сравнение текста
Вы также можете сравнить текст, аналогично сравнению чисел:
Сравнивая текст, вы должны помнить о «регистре» (верхний или нижний). По умолчанию VBA считает буквы с разными регистрами несоответствующими. Другими словами, «А» «а».Если вы хотите, чтобы VBA игнорировал регистр, вы должны добавить объявление Option Compare Text в верхнюю часть модуля:
После этого объявления «А» = «а»:
12345 | Вариант Сравнить текстSub If_Text ()MsgBox «a» = «A»Конец подписки |
VBA, если нравится
Оператор Like VBA позволяет проводить неточные сравнения текста. Щелкните ссылку «Like Operator», чтобы узнать больше, но мы покажем базовый пример ниже:
12345678 | Dim strName as StringstrName = «Мистер Чарльз»Если strName Like «Mr *» ТогдаMsgBox «True»ЕщеMsgBox «False»Конец, если |
Здесь мы используем подстановочный знак звездочки «*». * Обозначает любое количество любых символов. Таким образом, приведенный выше оператор If вернет ИСТИНА. Оператор Like — чрезвычайно мощный, но часто недостаточно используемый инструмент для работы с текстом.
Если петли
Циклы VBA позволяют повторять действия. Комбинирование IF-ELSE с циклами — отличный способ быстро обработать многие вычисления.
Продолжая наш пример Положительного / Отрицательного, мы добавим цикл For Each Loop для перебора диапазона ячеек:
1234567891011121314 | Sub If_Loop ()Тусклая ячейка как диапазонДля каждой ячейки в диапазоне («A2: A6»)Если Cell.Value> 0, тоCell.Offset (0, 1) .Value = «Положительный»ElseIf Cell.Value <0 ТогдаCell.Offset (0, 1) .Value = «Отрицательное»ЕщеCell.Offset (0, 1) .Value = «Ноль»Конец, еслиСледующая ячейкаКонец подписки |
Если остальные примеры
Теперь перейдем к более конкретным примерам.
Проверить, пуста ли ячейка
Этот код проверяет, пуста ли ячейка. Если он пуст, он проигнорирует ячейку. Если он не пустой, он выведет значение ячейки в ячейку справа:
1234567 | Sub If_Cell_Empty ()Если Range («a2»). Value «» ThenДиапазон («b2»). Значение = Диапазон («a2»). ЗначениеКонец, еслиКонец подписки |
Проверьте, содержит ли ячейка определенный текст
Функция Instr проверяет, найдена ли строка текста в другой строке. Используйте его с оператором If, чтобы проверить, содержит ли ячейка определенный текст:
123 | Если Instr (Range («A2»). Value, «text»)> 0, тоMsgbox «Текст найден»Конец, если |
Проверить, содержит ли ячейка текст
Этот код проверит, является ли ячейка текстом:
1234567 | Sub If_Cell_Is_Text ()Если Application.WorksheetFunction.IsText (Range («a2»). Value), тоMsgBox «Ячейка — это текст»Конец, еслиКонец подписки |
Если Goto
Вы можете использовать результат оператора If, чтобы «перейти к» другому разделу кода.
12345678910 | Sub IfGoTo ()Если IsError (Cell.value), тоПерейти к пропускуКонец, если’Некоторый кодПропускать:Конец подписки |
Удалить строку, если ячейка пуста
Используя If и циклы, вы можете проверить, пуста ли ячейка, и, если да, удалить всю строку.
123456789 | Sub DeleteRowIfCellBlank ()Тусклая ячейка как диапазонДля каждой ячейки в диапазоне («A2: A10»)Если Cell.Value = «» Тогда Cell.EntireRow.DeleteСледующая ячейкаКонец подписки |
Если MessageBox Да / Нет
С помощью окон сообщений VBA вы можете попросить пользователя выбрать один из нескольких вариантов. Окно сообщения Да / Нет предлагает пользователю выбрать Да или Нет. Вы можете добавить Окно сообщения Да / Нет в процедуру, чтобы спросить пользователя, хотят ли они продолжить выполнение процедуры или нет. Вы обрабатываете ввод пользователя с помощью оператора If.Вот окно сообщения Да / Нет на практике:
123456789101112 | Sub MsgBoxVariable ()Тусклый ответ как целое числоanswer = MsgBox («Продолжить?», vbQuestion + vbYesNo)Если answer = vb Да ТогдаMsgBox «Да»ЕщеMsgBox «Нет»Конец, еслиКонец подписки |
VBA If, ElseIf, Else в Access VBA
Функции If, ElseIf и Else в Access VBA работают точно так же, как и в Excel VBA.
Вы можете использовать оператор If, чтобы проверить, есть ли записи в наборе записей.
Author: Oscar Cronquist Article last updated on February 07, 2022
This article demonstrates how to use the If … Then statement in Visual Basic for Applications (VBA). You can combine the If … Then statement with Else and ElseIf to make it more versatile and create more advanced conditions.
Table of Contents
- How to use the If … Then statement (VBA)
- If … Then condition: larger than
- If … Then condition: equal to
- If … Then condition: not equal to
- How to use the If … Then … End If statement (VBA)
- How to use the If Then Else Endif statement (VBA)
- How to use the If Then Elseif Else End if statement (VBA)
- Where to put the code?
- How to run a macro
- Get Excel *.xlsx file
1. How to use the If … then statement
The picture above demonstrates an If … Then statement using a condition, you can use logical operators like the:
- < less than sign
- > greater than sign
- = equal sign
- <> not equal signs meaning a smaller than and a larger than sign combined.
This particular example checks if the value in B3 is smaller than the value in cell D3. If true the If statement runs the remaining code after the Then statement, in this case, it shows a message box with text Value1 is smaller than Value2. See the image above.
VBA code
'Name macro Sub Macro1() 'If ... Then statement If Range("B3") < Range("D3") Then MsgBox "Value1 is smaller than Value2" 'Stop macro End Sub
Where to put the code?
How to run a macro?
Back top
1.1 If … Then condition: larger than
VBA code
'Name macro Sub Macro1() 'If ... Then statement If Range("B3") > Range("D3") Then MsgBox "Value1 is larger than Value2" 'Stop macro End Sub
Where to put the code?
How to run a macro?
Back top
1.2 If … Then condition: equal to
VBA code
'Name macro Sub Macro1() 'If ... Then statement If Range("B3") = Range("D3") Then MsgBox "Value1 is equal to Value2" 'Stop macro End Sub
Where to put the code?
How to run a macro?
Back top
1.3 If … Then condition: not equal to
VBA code
'Name macro Sub Macro1() 'If ... Then statement If Range("B3") <> Range("D3") Then MsgBox "Value1 is not equal to Value2" 'Stop macro End Sub
Where to put the code?
How to run a macro?
Back to top
2. How to use the If … Then … End If statement
The If … Then … End If statement allows you to run multiple lines of code, the End if statement tells the subroutine when the lines have been run and the If … Then … End if statement is completed.
2.1 VBA code
'Name macro Sub Macro2() 'If ... Then ... Endif statement If Range("B3") < Range("D3") Then 'Save number 45 to cell E3 in current worksheet Range("E3") = 45 'Show message box MsgBox "Value1 is smaller than Value2" End if 'Stop macro End Sub
The subroutine above saves the number 45 to cell E3 if the value in cell B3 is smaller than the value in D3.
The msgbox function then displays a dialog box containing the message Value1 is smaller than Value2.
Where to put the code?
How to run a macro?
Back to top
3. How to use the If … Then … Else … End if statement
The ELSE statement allows you to run code if the logical expression is not met.
3.1 VBA code
'Name macro Sub Macro3() 'If ... Then ... Else ... Endif statement If Range("B3") < Range("D3") Then 'Display message box MsgBox "Value1 is smaller than Value2" Else 'Display message box MsgBox "Value1 is not smaller than Value2" End If 'Stop macro End Sub
Where to put the code?
How to run a macro?
Back to top
4. How to use the If … Then … Elseif … Else … Endif statement
The ELSEIF statement lets you create another logical expression, you may have multiple ELSEIFs in the statement.
4.1 VBA code
'Name macro Sub Macro4() 'If ... Then ... ElseIf ... Else ... Endif statement If Range("B3") < Range("D3") Then 'Display message box MsgBox "Value1 is smaller than Value2" ElseIf Range("B3") = Range("D3") Then 'Display message box MsgBox "Value1 is equal to Value2" Else 'Display message box MsgBox "Value1 is larger than Value2" End If 'Stop macro End Sub
Where to put the code?
How to run a macro?
Back to top
5. Where to put the VBA code?
- Copy the VBA macro code.
- Press Alt and F11 to open the Visual Basic Editor (VBE).
- Press with left mouse button on «Insert» on the top menu.
- Press with left mouse button on «Module», see the image above.
- A new module is inserted, see the Project Explorer above.
- Paste the VBA macro code to the code module.
- Exit VBE and return to Excel.
6. How to run a VBA macro
- Press Alt and F8, a dialog box appears.
- Select the macro you want to run.
- Press with left mouse button on «Run» button.
Get Excel *.xlsm macro-enabled file
IF THEN ELSE ENDIF.xlsm
Back to top
Latest updated articles.
More than 300 Excel functions with detailed information including syntax, arguments, return values, and examples for most of the functions used in Excel formulas.
More than 1300 formulas organized in subcategories.
Excel Tables simplifies your work with data, adding or removing data, filtering, totals, sorting, enhance readability using cell formatting, cell references, formulas, and more.
Allows you to filter data based on selected value , a given text, or other criteria. It also lets you filter existing data or move filtered values to a new location.
Lets you control what a user can type into a cell. It allows you to specifiy conditions and show a custom message if entered data is not valid.
Lets the user work more efficiently by showing a list that the user can select a value from. This lets you control what is shown in the list and is faster than typing into a cell.
Lets you name one or more cells, this makes it easier to find cells using the Name box, read and understand formulas containing names instead of cell references.
The Excel Solver is a free add-in that uses objective cells, constraints based on formulas on a worksheet to perform what-if analysis and other decision problems like permutations and combinations.
An Excel feature that lets you visualize data in a graph.
Format cells or cell values based a condition or criteria, there a multiple built-in Conditional Formatting tools you can use or use a custom-made conditional formatting formula.
Lets you quickly summarize vast amounts of data in a very user-friendly way. This powerful Excel feature lets you then analyze, organize and categorize important data efficiently.
VBA stands for Visual Basic for Applications and is a computer programming language developed by Microsoft, it allows you to automate time-consuming tasks and create custom functions.
A program or subroutine built in VBA that anyone can create. Use the macro-recorder to quickly create your own VBA macros.
UDF stands for User Defined Functions and is custom built functions anyone can create.
A list of all published articles.
In this Article
- VBA If Statement
- If Then
- ElseIF – Multiple Conditions
- Else
- If-Else
- Nested IFs
- IF – Or, And, Xor, Not
- If Or
- If And
- If Xor
- If Not
- If Comparisons
- If – Boolean Function
- Comparing Text
- VBA If Like
- If Loops
- If Else Examples
- Check if Cell is Empty
- Check if Cell Contains Specific Text
- Check if cell contains text
- If Goto
- Delete Row if Cell is Blank
- If MessageBox Yes / No
- VBA If, ElseIf, Else in Access VBA
VBA If Statement
If Then
VBA If Statements allow you to test if expressions are TRUE or FALSE, running different code based on the results.
Let’s look at a simple example:
If Range("a2").Value > 0 Then Range("b2").Value = "Positive"
This tests if the value in Range A2 is greater than 0. If so, setting Range B2 equal to “Positive”
Note: When testing conditions we will use the =, >, <, <>, <=, >= comparison operators. We will discuss them in more detail later in the article.
Here is the syntax for a simple one-line If statement:
If [test_expression] then [action]
To make it easier to read, you can use a Line Continuation character (underscore) to expand the If Statements to two lines (as we did in the above picture):
If [test_expression] then _
[action]
If Range("a2").Value > 0 Then _
Range("b2").Value = "Positive"
End If
The above “single-line” if statement works well when you are testing one condition. But as your IF Statements become more complicated with multiple conditions, you will need to add an “End If” to the end of the if statement:
If Range("a2").Value > 0 Then
Range("b2").Value = "Positive"
End If
Here the syntax is:
If [test_expression] then
[action]
End If
The End If signifies the end of the if statement.
Now let’s add in an ElseIF:
ElseIF – Multiple Conditions
The ElseIf is added to an existing If statement. ElseIf tests if a condition is met ONLY if the previous conditions have not been met.
In the previous example we tested if a cell value is positive. Now we will also test if the cell value is negative with an ElseIf:
If Range("a2").Value > 0 Then
Range("b2").Value = "Positive"
ElseIf Range("a2").Value < 0 Then
Range("b2").Value = "Negative"
End If
You can use multiple ElseIfs to test for multiple conditions:
Sub If_Multiple_Conditions()
If Range("a2").Value = "Cat" Then
Range("b2").Value = "Meow"
ElseIf Range("a2").Value = "Dog" Then
Range("b2").Value = "Woof"
ElseIf Range("a2").Value = "Duck" Then
Range("b2").Value = "Quack"
End If
End Sub
Now we will add an Else:
Else
The Else will run if no other previous conditions have been met.
We will finish our example by using an Else to indicate that if the cell value is not positive or negative, then it must be zero:
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-Else
The most common type of If statement is a simple If-Else:
Sub If_Else()
If Range("a2").Value > 0 Then
Range("b2").Value = "Positive"
Else
Range("b2").Value = "Not Positive"
End If
End Sub
Nested IFs
You can also “nest” if statements inside of each other.
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
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
IF – Or, And, Xor, Not
Next we will discuss the logical operators: Or, And, Xor, Not.
If Or
The Or operator tests if at least one condition is met.
The following code will test if the value in Range A2 is less than 5,000 or greater than 10,000:
If Range("a2").Value < 5000 Or Range("a2").Value > 10000 Then
Range("b2").Value = "Out of Range"
End If
You can include multiple Ors in one line:
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 you are going to use multiple Ors, it’s recommended to use a line continuation character to make your code easier to read:
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
The And operator allows you to test if ALL conditions are met.
If Range("a2").Value >= 5000 And Range("a2").Value <= 10000 Then
Range("b2").Value = "In Range"
End If
VBA Programming | Code Generator does work for you!
If Xor
The Xor operator allows you to test if exactly one condition is met. If zero conditions are met Xor will return FALSE, If two or more conditions are met, Xor will also return false.
I’ve rarely seen Xor used in VBA programming.
If Not
The Not operator is used to convert FALSE to TRUE or TRUE To FALSE:
Sub IF_Not()
MsgBox Not (True)
End Sub
Notice that the Not operator requires parenthesis surrounding the expression to switch.
The Not operator can also be applied to If statements:
If Not (Range("a2").Value >= 5000 And Range("a2").Value <= 10000) Then
Range("b2").Value = "Out of Range"
End If
If Comparisons
When making comparisons, you will usually use one of the comparison operators:
Comparison Operator | Explanation |
---|---|
= | Equal to |
<> | Not Equal to |
> | Greater than |
>= | Greater than or Equal to |
< | Less than |
<= | Less than or Equal to |
However, you can also use any expression or function that results in TRUE or FALSE
If – Boolean Function
When build expressions for If Statements, you can also use any function that generates TRUE or False. VBA has a few of these functions:
Function | Description |
---|---|
IsDate | Returns TRUE if expression is a valid date |
IsEmpty | Check for blank cells or undefined variables |
IsError | Check for error values |
IsNull | Check for NULL Value |
IsNumeric | Check for numeric value |
They can be called like this:
If IsEmpty(Range("A1").Value) Then MsgBox "Cell Empty"
Excel also has many additional functions that can be called using WorksheetFunction. Here’s an example of the Excel IsText Function:
If Application.WorksheetFunction.IsText(Range("a2").Value) Then _
MsgBox "Cell is Text"
You can also create your own User Defined Functions (UDFs). Below we will create a simple Boolean function that returns TRUE. Then we will call that function in our If statement:
Sub If_Function()
If TrueFunction Then
MsgBox "True"
End If
End Sub
Function TrueFunction() As Boolean
TrueFunction = True
End Function
Comparing Text
You can also compare text similar to comparing numbers:
Msgbox "a" = "b"
Msgbox "a" = "a"
When comparing text, you must be mindful of the “Case” (upper or lower). By default, VBA considers letters with different cases as non-matching. In other words, “A” <> “a”.
If you’d like VBA to ignore case, you must add the Option Compare Text declaration to the top of your module:
Option Compare Text
After making that declaration “A” = “a”:
Option Compare Text
Sub If_Text()
MsgBox "a" = "A"
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
VBA If Like
The VBA Like Operator allows you to make inexact comparisons of text. Click the “Like Operator” link to learn more, but we will show a basic example below:
Dim strName as String
strName = "Mr. Charles"
If strName Like "Mr*" Then
MsgBox "True"
Else
MsgBox "False"
End If
Here we’re using an asterisk “*” wildcard. The * stands for any number of any characters. So the above If statement will return TRUE. The Like operator is an extremely powerful, but often under-used tool for dealing with text.
If Loops
VBA Loops allow you to repeat actions. Combining IF-ELSEs with Loops is a great way to quickly process many calculations.
Continuing with our Positive / Negative example, we will add a For Each Loop to loop through a range of cells:
Sub If_Loop()
Dim Cell as Range
For Each Cell In Range("A2:A6")
If Cell.Value > 0 Then
Cell.Offset(0, 1).Value = "Positive"
ElseIf Cell.Value < 0 Then
Cell.Offset(0, 1).Value = "Negative"
Else
Cell.Offset(0, 1).Value = "Zero"
End If
Next Cell
End Sub
If Else Examples
Now we will go over some more specific examples.
Check if Cell is Empty
This code will check if a cell is empty. If it’s empty it will ignore the cell. If it’s not empty it will output the cell value to the cell to the right:
Sub If_Cell_Empty()
If Range("a2").Value <> "" Then
Range("b2").Value = Range("a2").Value
End If
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Check if Cell Contains Specific Text
The Instr Function tests if a string of text is found in another string. Use it with an If statement to check if a cell contains specific text:
If Instr(Range("A2").value,"text") > 0 Then
Msgbox "Text Found"
End If
Check if cell contains text
This code will test if a cell is text:
Sub If_Cell_Is_Text()
If Application.WorksheetFunction.IsText(Range("a2").Value) Then
MsgBox "Cell is Text"
End If
End Sub
If Goto
You can use the result of an If statement to “Go to” another section of code.
Sub IfGoTo ()
If IsError(Cell.value) Then
Goto Skip
End If
'Some Code
Skip:
End Sub
Delete Row if Cell is Blank
Using Ifs and loops you can test if a cell is blank and if so delete the entire row.
Sub DeleteRowIfCellBlank()
Dim Cell As Range
For Each Cell In Range("A2:A10")
If Cell.Value = "" Then Cell.EntireRow.Delete
Next Cell
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
If MessageBox Yes / No
With VBA Message Boxes you’re able to ask the user to select from several options. The Yes/No Message Box asks the user to select Yes or No. You can add a Yes / No Message Box to a procedure to ask the user if they would like to continue running the procedure or not. You handle the user’s input using an If statement.
Here is the Yes/No Message Box in practice:
Sub MsgBoxVariable()
Dim answer As Integer
answer = MsgBox("Do you want to Continue?", vbQuestion + vbYesNo)
If answer = vbYes Then
MsgBox "Yes"
Else
MsgBox "No"
End If
End Sub
VBA If, ElseIf, Else in Access VBA
The If, ElseIf and Else functions work exactly the same in Access VBA as in Excel VBA.
You can use an If statement to check if there are records in a Recordset.
If you want to be an advanced VBA user then an IF statement is a must-learn. And, I believe that you are already familiar with the word IF and you are frequently using it as a worksheet function.
In VBA, IF works just like the same. Its basic idea is to perform a task when a condition is TRUE else do nothing or do something else. You can write simply as well as in complex conditions.
For understanding purposes, I have split it into three different parts.
- A condition to test.
- A task to perform if the condition is TRUE.
- A task to perform if the condition is FALSE.
This is what it looks like in real life:
In the above example, rain is a condition. If this condition is TRUE, the boy will open his umbrella and if the condition is FALSE he will wear his hat. Conditions are everywhere in our day-to-day life. But now, let’s back to our coding world and explore it.
Syntax: VBA IF
We have three different types of IF statements in VBA.
1. IF-Then
IF THEN is the simplest form of an IF statement. All we need to do is specify a condition to check and if that condition is TRUE it will perform a task. But, if that condition is FALSE it will do nothing and skip the line instantly.
Syntax
IF condition Then statement[s]
In the above syntax, we have to specify a condition to evaluate and a task to perform if that condition is TRUE.
Example
In the above example, we have used verified that cell A1 has value 10 in it and if it has, the statement will show a message box with the message “Cell A1 has value 10”.
Sub CheckValue()
If Range("A1").Value = 10 Then
MsgBox ("Cell A1 has value 10")
End Sub
2. IF-Then-Else
You can use the IF-Then-Else statement where you want to perform a specific task if a condition is TRUE and a different task if a condition is FALSE.
Syntax
IF Condition Then
Statement[s]
Else
Statement[s]
End If
With the above syntax, we can perform different tasks according to the result of a condition. If the condition is TRUE then it will perform the statement which you have mentioned after “Then” or if the condition is FALSE it will perform the statement which you have mentioned after “Else”.
Example
Sub CheckValue()
If Range("A1").Value = "10" Then
MsgBox ("Cell A1 has value 10")
Else
MsgBox ("Cell A1 has a value other than 10")
End Sub
In the above example, I have used the IF-Then-Else statement to check the value in cell A1.
If cell A1 has a value of 10, you will get a message box showing “Cell A1 has a value of 10” and if there is any other value in cell A1 you get a message box showing “Cell A1 has a value other than 10”. So, here we are able to perform different tasks according to the result of the condition.
3. IF-Then-Elseif-Else
This is the most useful and important type of IF which will help you to write advanced condition statements. In this type, you can specify the second condition after evaluating your first condition.
Syntax
IF Condition Then
Statement[s]
Elseif Condition Then
Statement[s]
Else
Statement[s]
End If
In the above syntax, we have:
- A condition to evaluate.
- A statement to perform if that condition is TURE.
- If that condition is FALSE then we have the second condition to evaluate.
- And, if the second condition is TRUE we have a statement to perform.
- But, if both conditions, first and second are FALSE then it will perform a statement that you have mentioned after “Else”.
And, the best part is you can use any number of “Elseif” in your code. That means you can specify any number of conditions in your statement.
Example
Sub check_grade()
If Range("A2").Value = "A" Then
MsgBox "Very Good"
Else
If Range("A2").Value = "B" Then
MsgBox "Good"
ElseIf Range("A2").Value = "C" Then
MsgBox "Average"
ElseIf Range("A2").Value = "D" Then
MsgBox "Poor"
ElseIf Range("A2").Value = "E" Then
MsgBox "Very Poor"
Else
MsgBox "Enter Correct Grade"
End Sub
In the above example, we have written a macro that will first check cell A2 for the value “A” and if the cell has the grade “A”, the statement will return the message “Very Good”.
This statement will first check cell A2 for value “A” and if the cell has the grade “A”, the statement will return the message “Very Good”.
And, if the first condition is FALSE then it will evaluate the second condition and return the message “Good” if the cell has a grade of “B”.
And, if the second condition is false then it will go to the third condition and so on. In the end, if all five conditions are false it will run the code which I have written after else.
The secret about writing an IF statement in VBA
Now, you know about all the types of IF and you are also able to choose one of them according to the task you need to perform. Let me tell you a secret.
One Line IF statement Vs. Block IF statement
You can write an IF statement in two different ways and both have advantages and disadvantages. Have a look.
1. One Line Statement
The one-line statement is perfect if you are using the IF-Then statement. The basic to use one line statement is to write your entire code in one line.
If A1 = 10 Then Msgbox("Cell A1 has value 10")
In the above statement, we have written an IF statement to evaluate if cell A1 has a value of 10 then it will show a message box. The best practice to use one line statement is when you have to write a simple code. Using one-line code for complex and lengthy statements is hard to understand.
[icon name=”lightbulb-o” unprefixed_] Quick Tip: While writing single-line code you don’t need to use Endif to end the statement.
2. Block Statement
A Block statement is perfect when you want to write your code in a decent and understandable way. When you writing a block statement you can use multiple lines in your macro which give you a neat and clean code.
Sub check_value()
If Range(“A1”).Value = “10” Then
MsgBox ("Cell A1 has value 10")
Else
MsgBox ("Cell A1 has a value other than 10")
End If
End Sub
In the above example, we have written an IF-Then-Else statement in blocks. And, you can see that it is easy to read and even easy to debug.
When you will write complex statements (which you will definitely do after reading this guide) using block statements are always good. And, while writing nested If statements you can also add indentation in your line for more clarity.
[icon name=”lightbulb-o” unprefixed_] Quick Tip – You have an exception that you can skip using Else at the end of your code when you are using IF-Then-Elseif-Else. This is very helpful when you do not need to perform any task when none of the conditions is TRUE in your statement.
8 Real Life Examples
Here I have listed some simple but useful examples which you can follow along.
1. Nested IF
The best part of the IF statement is you create nesting statements. You can add a second condition in the first condition.
Sub NestIF()
Dim res As Long
res = MsgBox("Do you want to save this file?", vbYesNo, "Save File")
If res = vbYes Then 'start of first IF statement
If ActiveWorkbook.Saved <> True Then 'start of second IF statement.
ActiveWorkbook.SaveMsgBox ("Workbook Saved")
Else
MsgBox "This workbook is already saved"
End If 'end of second IF statement
Else
MsgBox "Make Sure to save it later"
End If ' end of first IF statement
End Sub
In the above example, we have used a nested IF statement. When you run this macro you will get a message box with the OK and Cancel options. Work of conditional statement starts after that.
First, it will evaluate which button you have clicked. If you clicked “Yes” then nest it will evaluate whether your worksheet is saved or not.
If your workbook is not saved, it will save it and you will get a message. And, if the workbook is already saved it will show a message about that.
But, If you click on the button the condition of the first macro will be FALSE and you will only get a message to save your book later.
The basic idea in this code is that the second condition is totally dependent on the first condition if the first condition is FALSE then the second condition will not get evaluated.
More on Nested IF
2. Create Loop With IF and GoTo
You can also create a loop by using goto with IF. Most programmers avoid writing loops this way as we have better ways for a loop. But there is no harm to learn how we can do this.
Sub auto_open()
Alert: If InputBox("Enter Username") <> "Puneet" Then
GoTo Alert
Else
MsgBox "Welcome"
End If
End Sub
In the above example, we have used a condition statement to create a loop. We have used auto_open as the name of the macro so that whenever anyone opens the file it will run that macro.
The user needs to enter a username and if that username is not equal to “Puneet” it will repeat the code and show the input box again. And, if you enter the right text then he/she will be able to access the file.
3. Check if a Cell Contains a Number
Here we have used a condition to check whether the active cell contains a numeric value or not.
Sub check_number()
If IsNumeric(Range("B2").Value) Then
MsgBox "Yes, active cell has a number."
Else
MsgBox "No, active cell hasn't a number."
End If
End Sub
In the above example, I have written a condition by using the isnumeric function in VBA which is the same as the worksheet’s number function to check whether the value in a cell is a number or not.
If the value is a number it will return TRUE and you will get a message “Yes, Active Cell Has A Numeric Value”. And, if the value is non-number then you will get a message “No Numeric Value In Active Cell”.
4. Using OR and AND With IF
By using IF OR you can specify two or more conditions and perform a task if at least one condition is TRUE from all.
Sub UsingOR()
If Range("A1") < 70 Or Range("B1") < 70 Then
MsgBox "You Are Pass"
Else
If Range("A1") < 40 And Range("B1") < 40 Then
MsgBox "You Are Pass"
Else
MsgBox "You Are Fail"
End If
End If
End Sub
In the above example, in line 2, we have two conditions using the OR. If a student gets 70 marks in any of the subjects the result will be a “Pass”. And on line 7, we have two conditions using the AND operator. If a student gets more than 40 marks in both of the subjects the result will be “Pass”.
By using the IF AND you can specify more than one condition and perform a task if all the conditions are TRUE.
5. Using Not With IF
By using NOT in a condition you can change TRUE into FALSE and FALSE into TRUE.
VBA IF Not
Sub IF_Not()
If Range(“D1”) <= 40 And Not Range(“E1”) = “E” Then
MsgBox "You Are Pass."
Else
MsgBox "You Are Fail."
End If
End Sub
In the above example, we have used NOT in the condition. We have two cell with the subject score. In one cell score is in numbers and in another cell it has grades.
- If a student has marks above 40 in the first subject and above E grade in the second subject then he/she is a PASS.
- If a student has marks above 40 in the first subject and above E grade in the second subject then he/she is PASS.
So every time when a student’s marks are more than 40 and a grade other than E we will get a message “You are Pass” or else “You are Fail”.
6. IF Statement With a Checkbox
Now, here we are using a checkbox to run a macro.
Sub ship_as_bill()
If Range("D15") = True Then
Range("D17:D21") = Range("C17:C21")
Else
If Range(“D15”) = False Then
Range("D17:D21").ClearContents
Else
MsgBox (“Error!”)
End If
End If
End Sub
In the above example, we have used an IF statement to create a condition that if the checkbox is tick marked then range D17:D21 is equal to range C17:C21. And, if the checkbox is not ticked then range D17:D21 will be blank.
Using this technique we can use the billing address as the shipping address and if we need something else we can enter the address manually.
7. Check if a Cell is Merged
And here, we are writing a condition to get an alert if active cell is merged.
Sub MergeCellCheck()
If ActiveCell.MergeCells Then
MsgBox "Active Cell Is Merged"
Else
MsgBox "Active Cell Is Not Merged"
End If
End Sub
In the above code, we have used merge cells to check whether the active cell is merged or not. If the active cell is merged then the condition will return an alert for that.
8. Delete the Entire Row if a Cell is Blank
Here we are using IF to check whether a row is blank or not. And, if that row is blank statement will delete that particular row.
Sub DeleteRow()
If Application.CountA(ActiveCell.EntireRow) = 0 Then
ActiveCell.EntireRow.Delete
Else
MsgBox Application.CountA(ActiveCell.EntireRow) & "Cell(s) have values in this row"
End If
End Sub
In the above example, it will first check for the cells which have value in them. If the count of cells with a value is zero then the condition will delete the active row else return the alert showing the number of cells having value.
Conclusion
As I said it’s one of the most important parts of VBA and must learn if you want to master VBA. With the IF statement, you can write simple codes as well as complex codes. You can also use logical operators and write nested conditions.
I hope this guide will help you to write better codes.
Now tell me this. Do you write conditions in VBA frequently? What kind of codes do you write? Please share your views with me in the comment section. And, please don’t forget to share this guide with your friends.
Related: Exit IF
What is IF Else Statement in VBA?
The If Else or If Then Else statement of VBA executes a set of instructions depending on whether the specified condition is met or not. If the condition (logical test) is true, one set of actions is performed. However, if the condition is false, an alternative set of actions is performed.
For example, in a call center, an employee is given a target of making 50 outbound calls in a day. If he/she achieves the target, a sum of money is paid as an incentive. However, if the target is not achieved, no incentive is paid.
The condition here is x>=50. So, if x is greater than or equal to 50, an incentive is paid. Otherwise, it is not paid.
Hence, if the condition is true, the output should be the message “incentive paid.” Otherwise, the output should be the message “incentive not paid.” Rather than checking the number of calls made by each employee manually, one can use the If Else statement of VBA.
A condition is an expression that evaluates to true or false. It is placed between the If and Then keywords. To create a condition, the conditional operators like “equal to” (=), “not equal to” (<>), “greater than” (>), “less than” (<), “less than or equal to” (<=), and “greater than or equal to” (>=) are used.
The purpose of using the If Else statement is to evaluate a condition and perform an action accordingly. If the condition is true, the code following the If Then keywords is run. However, if the condition is false, the code following the Else keyword is run.
The If Else statement works in VBA and not in Excel. However, the logical test of the If Else statement works similar to that of the IF function of ExcelIF function in Excel evaluates whether a given condition is met and returns a value depending on whether the result is “true” or “false”. It is a conditional function of Excel, which returns the result based on the fulfillment or non-fulfillment of the given criteria.
read more.
Table of contents
- What is IF Else Statement in VBA?
- The Syntax of the VBA If Else Statement
- The Working of the VBA If Else Statement
- VBA IF Else Example
- Key Points
- Frequently Asked Questions
- Recommended Articles
The Syntax of the VBA If Else Statement
The syntax of the VBA If Else statement is stated as follows:
IF <Logical Test> Then If the Logical Test is TRUE Else If the Logical Test is FALSE End IF
The condition (logical test) is required, while the Else statement is optional.
The Working of the VBA If Else Statement
First, the VBA If Else statement checks the supplied logical test. If the supplied logical test is true, an action (task) is performed. However, if the test is false, an alternative action is performed. An action is performed by the execution of the code.
Let us understand the working of the If Else statement with the help of an example. We want to supply the condition 10>11 as the logical testA logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test.read more.
If the given condition is true, the output should be the message “10 is greater.” However, if the condition is false, the output should be the message “10 is lesser.”
To write the code, the details are specified as follows:
- Enter the task to be performed if the condition evaluates to true.
- Enter the keyword Else followed by an alternative task to be performed. This alternative task will be performed if the condition evaluates to false.
The code for the given example is written as follows:
Sub IF_Else_Example1() If 10 > 11 Then MsgBox "10 is greater" Else MsgBox "10 is lesser" End If End Sub
Execute the code and the result appears as shown in the succeeding image. Since the condition (10>11) evaluates to false, the message following the Else statement is returned. Hence, the output is “10 is lesser.”
It must be noted that the preceding code returns at least one of the specified messages. This implies that either the If block or the Else block is executed at a given time. Both these blocks cannot be executed together in a single run.
VBA IF Else Example
You can download this VBA If Else Excel Template here – VBA If Else Excel Template
The following table shows the cost price (in $ in column B) of seven products (column A). We want to find the status (column C) of each product based on its price. For this, the criteria are mentioned as follows:
- If the cost price>$50, the status should be “expensive.”
- If the cost price<$50, the status should be “not expensive.”
The logical test is cost price>50. If this condition is true, the output in column C should be “expensive.” However, if the given condition is false, the alternative result should be “not expensive.”
Prior to writing the code, copy and paste the preceding table to an Excel worksheet. The steps for writing the code are listed as follows:
Step 1: Start the sub procedure.
Sub IF_ELSE_Example2() End Sub
Step 2: Declare the variable “k” as an integer. So, the data type is integers.
Dim k As Integer
Step 3: Use the For Next loop to loop through the given cells and perform tasks on all of them.
The For Next loop is used because the code needs to be executed a specific number of times. Moreover, multiple cell values need to be tested.
Since the test needs to be conducted on rows 2 to 8, the For Next loop begins from 2 and runs till 8. The same is shown in the following code and image.
For k = 2 To 8 Next k
Step 4: Enter the logical test within the For Next loop. For this, open the If statement and select the first cell with the help of the cells property. The cells(k, 2) implies row “k” and column 2.
The same is shown in the following code and image.
If Cells(k, 2).Value > 50 Then
Step 5: Enter the action to be performed following the If Then statement.
If the value in cell (k, 2) is greater than 50 (the condition evaluates to true), the output should be “expensive” in the adjacent cell of column C.
The same is shown in the following code and image.
Cells(k, 3).Value = "Expensive"
Step 6: Enter the Else statement. This will run if the logical test (cost price>50) evaluates to false. Going by the Else statement, the cells (k, 3) must display the message “not expensive” if the cost price is less than $50.
The same is shown in the following code and image.
Sub IF_ELSE_Example2() Dim k As Integer For k = 2 To 8 If Cells(k, 2).Value > 50 Then Cells(k, 3).Value = "Expensive" Else Cells(k, 3).Value = "Not Expensive" End If Next k End Sub
Step 7: Run the code and the output appears, as shown in the following image. The code loops through rows 2 to 8, tests every value of column B, and arrives at a result accordingly.
Hence, the logical test for cells B2, B4, B6, and B8 evaluates to true. So, the status in the corresponding cells of column C appears as “expensive.”
For the remaining cells of column C, the status appears as “not expensive.” These are the ones whose related cost price is less than $50.
Likewise, the If Else statement can be used to obtain different results.
Key Points
The important points associated with the If Else statements of VBA are listed as follows:
- The Else statement runs if the logical test evaluates to false.
- For testing multiple conditions, use the ElseIf or nested If Then Else statements.
- For looping through multiple objects (like cells) and performing tasks on each one of them, use the VBA loopsA VBA loop in excel is an instruction to run a code or repeat an action multiple times.read more.
- If the code is long and split into multiple lines, use the End If statement to terminate the If Then Else block.
Frequently Asked Questions
1. Define the If Else statement of VBA.
The If Else statement of VBA executes a group of statements depending on the fulfillment or non-fulfillment of a condition. This condition or logical test is entered between the If and the Then keywords of the code.
The condition is an expression that evaluates to either true or false. If the condition is met (true), the code following the If Then statements is executed. If the condition is not met (false), the code following the Else statement is executed.
The If Else statements are used to perform a set of actions subject to the condition specified by the user. It is possible to test more than one condition at a given time with the help of the ElseIf statements.
Note: The If and Else blocks cannot be executed simultaneously in a single run.
2. State the syntax of the If Else statements of VBA.
There are two syntaxes of the If Else statements of VBA. These are stated as follows:
a. First syntax of the If Else statement
If condition [ Then ]
[ statements ]
Else
[ else statements ]
b. Second syntax of the If Else statement
If condition [ Then ]
[ statements ]
Else
[ else statements ]
End If
The condition in both the preceding syntaxes is required, while the Else statements are optional.
The difference between the two syntaxes is in the usage of the End If statement. The End If statement is used when the code extends into multiple lines.
The End If statement terminates the If Then Else block. In other words, the End If tells VBA where the execution of the If Then statements is to be ended.
3. How to use the If Else to test multiple conditions in VBA?
To test multiple conditions, the ElseIf statements are used. The syntax for the same is stated as follows:
If condition [ Then ]
[ statements ]
ElseIf elseifcondition [ Then ]
[ elseif statements ]
Else
[ else statements ]
End If
The ElseIf condition is required if ElseIf is being used. The ElseIf statements are optional. The preceding syntax works as follows:
a. First, the If condition is checked. If this condition is true, the code following the Then keyword is run. If this condition is false, the ElseIf condition is tested.
b. If the ElseIf condition is true, the ElseIf statements are executed. If the ElseIf condition is false, the statements following Else are run.
c. The execution of statements ends with the End If keyword.
Note: The user can add any number of ElseIf clauses to the If Then Else statement. However, an ElseIf clause must appear before an Else clause.
Recommended Articles
This has been a guide to VBA If Else. Here we discuss how to use the If Then Else Statement along with a practical example and downloadable Excel template. You may learn more about VBA from the following articles-
- How to Use Counter in VBA Excel?
- VBA Asc
- Boolean in Excel VBA
- VBA IIF
- VBA ByRef