Логические функции в vba excel

Операторы, использующиеся в VBA Excel для отрицания и сравнения логических выражений. Синтаксис, принимаемые значения, приоритет логических операторов.

Оператор «Not»

«Not» – это оператор логического отрицания (инверсия), который возвращает True, если условие является ложным, и, наоборот, возвращает False, если условие является истинным.

Синтаксис:

Таблица значений:

Условие Результат
True False
False True

Оператор «And»

«And» – это оператор логического умножения (логическое И, конъюнкция), который возвращает значение True, если оба условия являются истинными.

Синтаксис:

Результат = Условие1 And Условие2

Таблица значений:

Условие1 Условие2 Результат
True True True
True False False
False True False
False False False

Оператор «Or»

«Or» – это оператор логического сложения (логическое ИЛИ, дизъюнкция), который возвращает значение True, если одно из двух условий является истинным, или оба условия являются истинными.

Синтаксис:

Результат = Условие1 Or Условие2

Таблица значений:

Условие1 Условие2 Результат
True True True
True False True
False True True
False False False

Оператор «Xor»

«Xor» – это оператор логического исключения (исключающая дизъюнкция), который возвращает значение True, если только одно из двух условий является истинным.

Синтаксис:

Результат = Условие1 Xor Условие2

Таблица значений:

Условие1 Условие2 Результат
True True False
True False True
False True True
False False False

Оператор «Eqv»

«Eqv» – это оператор логической эквивалентности (тождество, равенство), который возвращает True, если оба условия имеют одинаковое значение.

Синтаксис:

Результат = Условие1 Eqv Условие2

Таблица значений:

Условие1 Условие2 Результат
True True True
True False False
False True False
False False True

Оператор «Imp»

«Imp» – это оператор логической импликации, который возвращает значение False, если первое (левое) условие является истинным, а второе (правое) условие является ложным, в остальных случаях возвращает True.

Синтаксис:

Результат = Условие1 Imp Условие2

Таблица значений:

Условие1 Условие2 Результат
True True True
True False False
False True True
False False True

Приоритет логических операторов

Приоритет определяет очередность выполнения операторов в одном выражении. Очередность выполнения логических операторов в VBA Excel следующая:

  1. «Not» – логическое отрицание;
  2. «And» – логическое И;
  3. «Or» – логическое ИЛИ;
  4. «Xor» – логическое исключение;
  5. «Eqv» – логическая эквивалентность;
  6. «Imp» – логическая импликация.

In this Article

  • Using the And Logical Operator
  • Using the Or Logical Operator
  • Using the Not Logical Operator
  • Using the Xor Logical Operator
  • Is Operator
  • Like Operator

VBA allows you to use the logical operators And, Or, Not, Xor to compare values. The operators are considered “Boolean”, which means they return True or False as a result.

If you want to learn how to compare strings, click here: VBA Compare Strings – StrComp

If you want to learn how to use comparison operators, click here: VBA Comparison Operators – Not Equal to & More

Using the And Logical Operator

The And logical operator compares two or more conditions. If all the conditions are true, the operator will return True. If at least one of the conditions is not true, the operator will return False. Here is an example:

Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
  
intA = 5
intB = 5
   
If intA = 5 And intB = 5 Then
    blnResult = True
Else
    blnResult = False
End If

In this example, we want to check if both intA and intB are equal to 5. If this is true, the value of Boolean blnResult will be True, otherwise, it will be False.

First, we set values of intA and intB to 5:

intA = 5
intB = 5

After that, we use the And operator in the If statement to check if the values are equal to 5:

If intA = 5 And intB = 5 Then
    blnResult = True
Else
    blnResult = False
End If

As both variables are equal to 5, the blnResult returns True:

vba logical operators and

Image 1. Using the And logical operator in VBA

Using the Or Logical Operator

The Or logical operator compares two or more conditions. If at least one of the conditions is true, it will return True. If none of the conditions are true, the operator will return False. Here is the code for the example:

Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean

intA = 5
intB = 10

If intA = 5 Or intB = 5 Then
    blnResult = True
Else
    blnResult = False
End If

In this example, we want to check if both intA is equal to 5. or intB is equal to 10. If any of these conditions is true, the value of Boolean blnResult will be True, otherwise, it will be False.

First, we set the value of intA to 5 and intB to 10:

intA = 5
intB = 10

After that, we use the Or operator in the If statement to check if any of the values is equal to 5:

If intA = 5 Or intB = 5 Then
    blnResult = True
Else
    blnResult = False
End If

As intA value is 5, the blnResult returns True:

vba logical operators or

Image 2. Using the Or logical operator in VBA

Using the Not Logical Operator

The Not logical operator checks one or more conditions. If the conditions are true, the operator returns False. Otherwise, it returns True. Here is the code for the example:

Dim intA As Integer
Dim blnResult As Boolean

intA = 5

If Not (intA = 6) Then
    blnResult = True
Else
    blnResult = False
End If

In this example, we want to check if the value of intA is not equal to 6. If intA is different than 6, the value of Boolean blnResult will be True, otherwise, it will be False.

First, we set the value of intA to 5:

intA = 5

After that, we use the Not operator in the If statement to check if the value of intA is different than 6:

If Not (intA = 6) Then
    blnResult = True
Else
    blnResult = False
End If

As intA value is 5, the blnResult returns True:

vba logical operators not

Image 3. Using the Not logical operator in VBA

Using the Xor Logical Operator

The Xor logical operator compares two or more conditions. If exactly one of the conditions is true, it will return True. If none of the conditions are true, or more than one are true, it will return False. Here is the code for the example:

Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean

intA = 5
intB = 10

If intA = 5 Xor intB = 5 Then
    blnResult = True
Else
    blnResult = False
End If

In this example, we want to check if exactly one of the values (intA or IntB) are equal to 5. If only one condition is true, the value of Boolean blnResult will be True, otherwise, it will be False.

First, we set the value of intA to 5 and intB to 10:

intA = 5
intB = 10

After that, we use the Or operator in the If statement to check if any of the values is equal to 5:

If intA = 5 Xor intB = 5 Then
    blnResult = True
Else
    blnResult = False
End If

As intA value is 5 and intB is 10, the blnResult returns True:

vba logical operators xor

Image 4. Using the Xor logical operator in VBA

Is Operator

The Is Operator tests if two object variables store the same object.

Let’s look at an example. Here we will assign two worksheets to worksheet objects rng1 and rng2, testing if the two worksheet objects store the same worksheet:

Sub CompareObjects()
Dim ws1 As Worksheet, ws2 As Worksheet

Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")

If ws1 Is ws2 Then
    MsgBox "Same WS"
Else
    MsgBox "Different WSs"
End If

End Sub

Of course the worksheet objects are not the same, so “Different WSs” is returned.

Like Operator

The Like Operator can compare two strings for inexact matches. This example will test if a string starts with “Mr.”

Sub LikeDemo()

Dim strName As String
Dim blnResult As Boolean

strName = "Mr. Michael James" 

If strName Like "Mr*" Then
    blnResult = True
Else
    blnResult = False
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!
vba save as

Learn More!

Logical operators are used for performing logical and asthmatic operations on a set of values or variables. The table depicts all the different types of logical operators supported by Excel:

Operator      Description

AND  

(LOGICAL AND)

If both the conditions are True, then the Expression is true.

Example:

Assume variable A holds 10 and variable B holds 0, then 

a<>0 AND b<>0 is False

OR

( Logical OR Operator)

If any of the two conditions are True, then the condition is true.

Example:

Assume variable A holds 10 and variable B holds 0, then 

a<>0 OR b<>0 is true.

NOT

( Logical NOT Operator)

Reverse the result. If a condition is true, then the Logical NOT operator will make false.

Example:

Assume variable A holds 10 and variable B holds 0, then 

NOT(a<>0 OR b<>0) is false.

XOR

( Logical XOR Operator)

It is the combination of NOT and OR Operator. If one, and only one, of the expressions, evaluate to be True, the result is True.

Example:

Assume variable A holds 10 and variable B holds 0, then 

(a<>0 XOR b<>0) is true

1. AND  (LOGICAL AND)

If both the conditions are True, then the Expression is true.

Example:

Assume variable A holds 20 and variable B holds 0, then a<>0 AND b<>0 is False

Program:

Private Sub Demo_Loop()

Dim a As Integer //Declaring variable

 a = 20

 Dim b As Integer  //Declaring variable

 b = 0

If a <> 0 And b <> 0 Then

MsgBox ("AND LOGICAL Operator Result is : True")

 Else

 MsgBox ("AND LOGICAL Operator Result is : False")

 End If

End Sub

Output:

AND LOGICAL Operator Result is : False

2. OR( Logical OR Operator)

If any of the two conditions are True, then the condition is true.

Example:

Assume variable A holds 20 and variable B holds 0, then a<>0 OR b<>0 is true.

Program:

Private Sub Demo_Loop()
Dim a As Integer //Declaring variable
a = 20
Dim b As Integer  //Declaring variable
b = 0
If a <> 0 Or b <> 0 Then
MsgBox ("OR LOGICAL Operator Result is : True")
Else
MsgBox ("OR LOGICAL Operator Result is : False")
End If
End Sub

Output:

OR LOGICAL Operator Result is : True

3. NOT( Logical NOT Operator)

Reverse the result. If a condition is true, then the Logical NOT operator will make false.

Example:

Assume variable A holds 20 and variable B holds 0, then NOT(a<>0 OR b<>0) is false.

Program:

Private Sub Demo_Loop()
Dim a As Integer //Declaring variable
a = 20
Dim b As Integer  //Declaring variable
b = 0
If a <> 0 Not b <> 0 Then
MsgBox ("NOT LOGICAL Operator Result is : True")
Else
MsgBox ("NOT LOGICAL Operator Result is : False")
End If
End Sub

Output:

NOT LOGICAL Operator Result is : False

4. XOR( Logical XOR Operator)

It is the combination of NOT and OR Operator. If one, and only one, of the expressions, evaluate to be True, the result is True.

Example:

Assume variable A holds 20 and variable B holds 0, then (a<>0 XOR b<>0) is true.

Program:

Private Sub Demo_Loop()
Dim a As Integer //Declaring variable
a = 20
Dim b As Integer  //Declaring variable
b = 0
If a <> 0 Xor b <> 0 Then
MsgBox ("XOR LOGICAL Operator Result is : True")
Else
MsgBox ("XOR LOGICAL Operator Result is : False")
End If
End Sub

Output:

XOR LOGICAL Operator Result is : True

A Sample Program showing all the Operators is included below along with the outputs:

Program:

 Private Sub Demo_Loop()
Dim a As Integer //Declaring variable
  a = 20
  Dim b As Integer  //Declaring variable
  b = 0
     
  If a <> 0 And b <> 0 Then
     MsgBox ("AND LOGICAL Operator Result is : True")
  Else
     MsgBox ("AND LOGICAL Operator Result is : False")
  End If
  If a <> 0 Or b <> 0 Then
     MsgBox ("OR LOGICAL Operator Result is : True")
  Else
     MsgBox ("OR LOGICAL Operator Result is : False")
  End If
  If Not (a <> 0 Or b <> 0) Then
     MsgBox ("NOT LOGICAL Operator Result is : True")
  Else
     MsgBox ("NOT LOGICAL Operator Result is : False")
  End If
  If (a <> 0 Xor b <> 0) Then
     MsgBox ("XOR  LOGICAL Operator Result is : True")
  Else
     MsgBox ("XOR LOGICAL Operator Result is : False")
  End If
End Sub

Output:

AND LOGICAL Operator Result is : False
OR LOGICAL Operator Result is : True
NOT LOGICAL Operator Result is : False
XOR LOGICAL Operator Result is : True

VBA Logical Operators: AND, OR, NOT

Let’s say you want to process a customer order. For that, you want to first check to see if the ordered product exists or not. If it does, you also want to check if the quantity on hand is enough. Logical operators come in handy in such cases. Logical operators are used to evaluate more than one condition.

The main Excel VBA logical operators AND, OR, NOT are listed in the table below:

S/N Operator Description Example Output
1 AND AND: This is used to combine more than one condition. If all the conditions are true, AND evaluates to true. If any of the condition is false, AND evaluates to false If true = true AND false = true THEN false
2 OR OR: This is used to combine more than one condition. If any of the conditions evaluate to true, OR returns true. If all of them are false, OR returns false If true = true OR true = false THEN true
3 NOT NOT: This one works like an inverse function. If the condition is true, it returns false, and if a condition is false, it returns true. If NOT (true) Then false

VBA Logical Operators Example Source Code

For the sake of simplicity, we will be comparing hard coded numbers.

Add ActiveX buttons to the sheet from the “Insert option.”

Set the properties as shown in the image below

VBA Logical Operators

VBA Logical Operators

The following table shows the properties that you need to change and the values that you need to update too.

S/N Control Property Value
1 CommandButton1 Name btnAND
Caption AND Operator (0 = 0)
2 CommandButton2 Name btnOR
Caption OR Operator (1 = 1) Or (5 = 0)
3 CommandButton3 Name btnNOT
Caption NOT Operator Not (0 = )

Add the following code to btnAND_Click

Private Sub btnAND_Click()
    If (1 = 1) And (0 = 0) Then
            MsgBox "AND evaluated to TRUE", vbOKOnly, "AND operator"
        Else
            MsgBox "AND evaluated to FALSE", vbOKOnly, "AND operator"
    End If
End Sub

VBA If AND Operator

  • “If (1 = 1) And (0 = 0) Then” the if statement uses the AND logical operator to combine two conditions (1 = 1) And (0 = 0). If both conditions are true, the code above ‘Else’ keyword is executed. If both conditions are not true, the code below ‘Else’ keyword is executed.

Add the following code to btnOR_Click

Private Sub btnOR_Click()
    If (1 = 1) Or (5 = 0) Then
            MsgBox "OR evaluated to TRUE", vbOKOnly, "OR operator"
        Else
            MsgBox "OR evaluated to FALSE", vbOKOnly, "OR operator"
    End If
End Sub

VBA If OR Operator

  • “If (1 = 1) Or (5 = 0) Then” the if statement uses the OR logical operator to combine two conditions (1 = 1) And (5 = 0). If any of the conditions is true, the code above Else keyword is executed. If both conditions are false, the code below Else keyword is executed.

Add the following code to btnNOT_Click

Private Sub btnNOT_Click()
    If Not (0 = 0) Then
            MsgBox "NOT evaluated to TRUE", vbOKOnly, "NOT operator"
        Else
            MsgBox "NOT evaluated to FALSE", vbOKOnly, "NOT operator"
    End If
End Sub

VBA If NOT Operator

  • “If Not (0 = 0) Then” the VBA If Not function uses the NOT logical operator to negate the result of the if statement condition. If the conditions is true, the code below ‘Else’ keyword is executed. If the condition is true, the code above Else keyword is executed.

Download Excel containing above code

На чтение 6 мин Опубликовано 15.12.2015

Содержание

  1. Операторы Excel VBA
  2. Математические операторы
  3. Строковые операторы
  4. Операторы сравнения
  5. Логические операторы
  6. Встроенные функции

Операторы Excel VBA

При написании кода VBA в Excel набор встроенных операторов используют на каждом шагу. Эти операторы делятся на математические, строковые, операторы сравнения и логические. Далее мы подробно рассмотрим каждую группу операторов.

Математические операторы

Основные математические операторы VBA перечислены в таблице ниже.

В правом столбце таблицы указан приоритет операторов, принятый по умолчанию при отсутствии скобок. Добавляя в выражение скобки, можно изменять порядок выполнения операторов VBA по своему желанию.

Оператор Действие Приоритет
(1 — высший; 5 — низший)
^ Оператор возведения в степень 1
* Оператор умножения 2
/ Оператор деления 2
Оператор деления без остатка – возвращает результат деления двух чисел без остатка. Например, 74 возвратит результат 1 3
Mod Оператор модуля (остатка) – возвращает остаток от деления двух чисел. Например, 8 Mod 3 возвратит результат 2. 4
+ Оператор сложения 5
Оператор вычитания 5

Строковые операторы

Основной строковый оператор в Excel VBA – это оператор конкатенации & (слияние):

Оператор Действие
& Оператор конкатенации. К примеру, выражение «A» & «B» возвратит результат AB.

Операторы сравнения

Операторы сравнения используются для сравнения двух чисел или строк и возвращают логическое значение типа Boolean (True или False). Основные операторы сравнения Excel VBA перечислены в этой таблице:

Оператор Действие
= Равно
<> Не равно
< Меньше
> Больше
<= Меньше либо равно
>= Больше либо равно

Логические операторы

Логические операторы, как и операторы сравнения, возвращают логическое значение типа Boolean (True или False). Основные логические операторы Excel VBA перечислены в таблице ниже:

Оператор Действие
And Операция конъюнкции, логический оператор И. Например, выражение A And B возвратит True, если A и B оба равны True, в противном случае возвратит False.
Or Операция дизъюнкции, логический оператор ИЛИ. Например, выражение A Or B возвратит True, если A или B равны True, и возвратит False, если A и B оба равны False.
Not Операция отрицания, логический оператор НЕ. Например, выражение Not A возвратит True, если A равно False, или возвратит False, если A равно True.

В приведённой выше таблице перечислены не все логические операторы, доступные в VBA. Полный список логических операторов можно найти на сайте Visual Basic Developer Center.

Встроенные функции

В VBA доступно множество встроенных функций, которые могут быть использованы при написании кода. Ниже перечислены некоторые из наиболее часто используемых:

Функция Действие
Abs Возвращает абсолютную величину заданного числа.

Пример:

  • Abs(-20) возвращает значение 20;
  • Abs(20) возвращает значение 20.
Chr Возвращает символ ANSI, соответствующий числовому значению параметра.

Пример:

  • Chr(10) возвращает перенос строки;
  • Chr(97) возвращает символ a.
Date Возвращает текущую системную дату.
DateAdd Добавляет определённый временной интервал к заданной дате. Синтаксис функции:

DateAdd(интервал, число, дата)

Где аргумент интервал определяет тип временного интервала, добавляемого к заданной дате в количестве, указанном в аргументе число.

Аргумент интервал может принимать одно из следующих значений:

Интервал Значение
yyyy год
q квартал
m месяц
y день года
d день
w день недели
ww неделя
h час
n минута
s секунда

Пример:

  • DateAdd(«d», 32, «01/01/2015») добавляет 32 дня к дате 01/01/2015 и, таким образом, возвращает дату 02/02/2015.
  • DateAdd(«ww», 36, «01/01/2015») добавляет 36 недель к дате 01/01/2015 и возвращает дату 09/09/2015.
DateDiff Вычисляет количество определённых временных интервалов между двумя заданными датами.

Пример:

  • DateDiff(«d», «01/01/2015», «02/02/2015») вычисляет количество дней между датами 01/01/2015 и 02/02/2015, возвращает результат 32.
  • DateDiff(«ww», «01/01/2015», «03/03/2016») вычисляет количество недель между датами 01/01/2015 и 03/03/2016, возвращает результат 61.
Day Возвращает целое число, соответствующее дню месяца в заданной дате.

Пример: Day(«29/01/2015») возвращает число 29.

Hour Возвращает целое число, соответствующее количеству часов в заданном времени.

Пример: Hour(«22:45:00») возвращает число 22.

InStr Принимает в качестве аргументов целое число и две строки. Возвращает позицию вхождения второй строки внутри первой, начиная поиск с позиции, заданной целым числом.

Пример:

  • InStr(1, «Вот искомое слово», «слово») возвращает число 13.
  • InStr(14, «Вот искомое слово, а вот еще искомое слово», «слово») возвращает число 38.

Примечание: Аргумент-число может быть не задан, в таком случае поиск начинается с первого символа строки, заданной во втором аргументе функции.

Int Возвращает целую часть заданного числа.

Пример: Int(5.79) возвращает результат 5.

Isdate Возвращает True, если заданное значение является датой, или False – если датой не является.

Пример:

  • IsDate(«01/01/2015») возвращает True;
  • IsDate(100) возвращает False.
IsError Возвращает True, если заданное значение является ошибкой, или False – если ошибкой не является.
IsMissing В качестве аргумента функции передаётся имя необязательного аргумента процедуры. IsMissing возвращает True, если для рассматриваемого аргумента процедуры не передано значение.
IsNumeric Возвращает True, если заданное значение может быть рассмотрено как число, в противном случае возвращает False.
Left Возвращает заданное количество символов от начала переданной строки. Синтаксис функции вот такой:

Left(строка, длина)

где строка – это исходная строка, а длина – количество возвращаемых символов, считая от начала строки.

Пример:

  • Left(«абвгдежзиклмн», 4) возвращает строку «абвг»;
  • Left(«абвгдежзиклмн», 1) возвращает строку «а».
Len Возвращает количество символов в строке.

Пример: Len(«абвгдеж») возвращает число 7.

Month Возвращает целое число, соответствующее месяцу в заданной дате.

Пример: Month(«29/01/2015») возвращает значение 1.

Mid Возвращает заданное количество символов из середины переданной строки. Синтаксис функции:

Mid(строка, начало, длина)

где строка – это исходная строка, начало – позиция начала извлекаемой строки, длина – количество символов, которые требуется извлечь.

Пример:

  • Mid(«абвгдежзиклмн», 4, 5) возвращает строку «гдежз»;
  • Mid(«абвгдежзиклмн», 10, 2) возвращает строку «кл».
Minute Возвращает целое число, соответствующее количеству минут в заданном времени.Пример: Minute(«22:45:15») возвращает значение 45.
Now Возвращает текущую системную дату и время.
Right Возвращает заданное количество символов от конца переданной строки. Синтаксис функции:

Right(строка, длина)

Где строка – это исходная строка, а длина – это количество символов, которые надо извлечь, считая от конца заданной строки.

Пример:

  • Right(«абвгдежзиклмн», 4) возвращает строку «клмн»;
  • Right(«абвгдежзиклмн», 1) возвращает строку «н».
Second Возвращает целое число, соответствующее количеству секунд в заданном времени.

Пример: Second(«22:45:15») возвращает значение 15.

Sqr Возвращает квадратный корень числовой величины, переданной в аргументе.

Пример:

  • Sqr(4) возвращает значение 2;
  • Sqr(16) возвращает значение 4.
Time Возвращает текущее системное время.
Ubound Возвращает верхний индекс измерения заданного массива.

Примечание: Для многомерных массивов в качестве необязательного аргумента может быть указано, индекс какого именно измерения нужо возвратить. Если не указано, то по умолчанию равно 1.

Year Возвращает целое число, соответствующее году в заданной дате.Пример: Year(«29/01/2015») возвращает значение 2015.

Данный список включает в себя только избранные наиболее часто употребляемые встроенные функции Excel Visual Basic. Исчерпывающий список функций VBA, доступных для использования в макросах Excel, можно найти на сайте Visual Basic Developer Center.

Оцените качество статьи. Нам важно ваше мнение:

IF OR is not a single statement. Rather, these are two logical functions used together in VBA when we have more than one criteria to check. When we use the IF statement, if any criteria meet, we get the TRUE result. OR statement is used between the two criteria of the IF statement.

IF OR Function in VBA

Logical functions are the heart of any criteria-based calculations. The IF function is the most popular logical function, be it a worksheet function or a VBA function because it serves excellently for our needs. But one more logical function, OR in excel, is the most underrated. It is also important to master when it comes to solving complex calculations. This article will take you through the VBA IF OR function in detail. Read the full article to get the function in detail.

Table of contents
  • IF OR Function in VBA
    • How to Use IF with OR Function in VBA?
    • IF OR VBA Function with Loops (Advanced)
    • Recommended Articles

VBA IF OR

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA IF OR (wallstreetmojo.com)

How to Use IF with OR Function in VBA?

We will show you a simple example of using the IF OR function in VBA.

You can download this VBA IF OR Excel Template here – VBA IF OR Excel Template

A combination of logical functions is the best pair in Excel. However, combining many logical formulas inside the other logical formula suggests that calculation requires many conditions to test.

Now, look at the syntax of the IF OR function in VBA.

[Test] OR [Test] OR [Test]

It is the same as we saw in the worksheet example. For a better understanding, look at the below example.

VBA IF OR Example 1

We have the previous month’s price, the last 6-month average price, and the current monthly price here.

To decide whether to buy the product, we need to do some tests here, and those tests are.

If the Current Price is less than or equal to any of the other two prices, we should get the result as “Buy” or else should get the result as “Do Not Buy.”

Step 1: Open the IF condition inside the Sub procedure.

Code:

Sub IF_OR_Example1()

 If

End Sub

VBA IF OR Example 1-1

Step 2: Inside the IF condition, apply the first logical test as Range(“D2”).Value <= Range(“B2”).Value

Code:

Sub IF_OR_Example1()

 If Range(“D2”).Value <= Range(“B2”).Value

End Sub

VBA IF OR Example 1-2

Step 3: The first logical condition completes. Now, open OR statement.

Code:

Sub IF_OR_Example1()

 If Range("D2").Value <= Range("B2").Value OR

End Sub

VBA IF OR Example 1-3

Step 4: Now, apply the second logical condition as Range(“D2”).Value <= Range(“C2”).Value

Code:

Sub IF_OR_Example1()

 If Range("D2").Value <= Range("B2").Value OR Range("D2").Value <= Range("C2").Value

End Sub

VBA IF OR Example 1-4

Step 5: We are done with the logical tests here. After the logical tests, put the word “Then.”

Code:

Sub IF_OR_Example1()

 If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then

End Sub

VBA IF OR Example 1-5

Step 6: In the next line, write what the result should be if 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 is TRUE. If the condition is TRUE, we need the result as “Buy” in cell E2.

Code:

Sub IF_OR_Example1()

 If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then  

    Range("E2").Value = "Buy"

End Sub

VBA IF OR Example 1-6

Step 7: If the result is FALSE, we should get the result as “Do Not Buy.” So in the next line, put “Else” and write the code in the next line.

Code:

Sub IF_OR_Example1()

If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then 

   Range("E2").Value = "Buy"
Else
   Range("E2").Value = "Do Not Buy"

End Sub

VBA IF OR Example 1-7

Step 8: Close the IF statement with “End If.”

Code:

Sub IF_OR_Example1()

If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then

   Range("E2").Value = "Buy"
Else
   Range("E2").Value = "Do Not Buy"
End If

End Sub

VBA IF OR Example 1-8

We complete the coding part.

Let us run this code using F5 or manually through the run option and see the result in cell E2.

Example 1-9

We got the result as “Buy” because the current monthly price of Apple is less than the price of both “Previous Month” as well as “6 Month Average Price”.

IF OR VBA Function with Loops (Advanced)

Once you understand the formula, try to use it with a larger number of cells. In the case of a larger number of cells, we cannot write any line of code, so we need to use VBA loopsA VBA loop in excel is an instruction to run a code or repeat an action multiple times.read more.

We have added a few more lines for the above data set.

Example 2

We need to use the For Next Loop here.

Just keep the current code as it is.

Declare the variable as an Integer.

Example 2-1

Now, open For Next Loop from 2 to 9.

Example 2-2

Now, wherever we have cell referenceCell reference in excel is referring the other cells to a cell to use its values or properties. For instance, if we have data in cell A2 and want to use that in cell A1, use =A2 in cell A1, and this will copy the A2 value in A1.read more, change the current number, and concatenate the variable “k” with them.

For example, Range (“D2”).Value should be Range (“D” & k).Value

Example 2-3

Now, run the code. First, we should get the status in all the cells.

Example 2-4

You can copy the code below.

Code:

Sub IF_OR_Example1()

Dim k As Integer

For k = 2 To 9

If Range("D" & k).Value <= Range("B" & k).Value Or Range("D" & k).Value <= Range("C" & k).Value Then

Range("E" & k).Value = "Buy"
Else

Range("E" & k).Value = "Do Not Buy"

End If

Next k

End Sub

Recommended Articles

This article has been a guide to VBA IF OR. Here, we learn how to use IF Condition with OR function in Excel VBA, examples, and downloadable templates. Below are some useful articles related to VBA: –

  • VBA INT
  • VBA LEN
  • VBA Integer
  • VBA MID Function

Понравилась статья? Поделить с друзьями:
  • Лучшая книга excel бесплатно
  • Логические функции в excel что это такое
  • Лучшая замена word на windows 10
  • Логические функции в excel функция истинности
  • Лучшая альтернатива microsoft word