Excel vba boolean and or

Операторы, использующиеся в 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» – логическая импликация.

Содержание

  1. Логические операторы VBA
  2. Логический оператор AND
  3. Логический оператор OR
  4. Логический оператор NOT
  5. Логический оператор XOR
  6. Логический оператор EQV
  7. Логический оператор IMP
  8. Логические и побитовые операторы в Visual Basic
  9. Унарный логический оператор
  10. Двоичные логические операторы
  11. логические операции Short-Circuiting
  12. Short-Circuiting Trade-Offs
  13. Битовые операции
  14. 3.4 Logical Operators in Excel VBA
  15. Boolean Values
  16. Logical Not
  17. Logical And

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

Оператор Синтаксис Описание
AND A AND B Конъюнкция: Если А и В имеют значение True, то — True. Иначе — False
OR A OR B Дизъюнкция: Если любой из операндов имеет значение True, то — True. Иначе — False
NOT NOT A Отрицание: Если А имеет значение False, то — True. Иначе — False
XOR A XOR B Исключение: Если А имеет значение True или В имеет значение True, то — True. Иначе — False
EQV A EQV B Эквивалентность: Если А имеет такое же значение что и В, то — True. Иначе — False
IMP A IMP B Импликация: Если А имеет значение True и В имеет значение False, то — False. Иначе — True

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

Результатом логической операции является значение типа Boolean (или Null, если хотя бы один из операндов имеет значение Null).

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

Синтаксис:
Операнд_1 AND Операнд_2

Оператор AND выполняет логическую конъюнкцию.

Результатом данной операции является значение True, только когда оба операнда имеют значение True, иначе — False.

Операнд_1 Операнд_2 Результат
True True True
True False False
False True False
False False False

Оператор AND можно использовать для нескольких операндов:

(5 3) AND (5=6) результатом будет False

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

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

Синтаксис:
Операнд_1 OR Операнд_2

Оператор OR выполняет логическую дизъюнкцию.

Результатом данной операции является значение True, если хотя бы один из операндов имеет значение True, иначе — False.

Операнд_1 Операнд_2 Результат
True True True
True False True
False True True
False False False

Оператор OR можно использовать для нескольких операндов:

(5 3) OR (5=6) результатом будет True

Независимо от количества операндов результатом логической операции OR будет всегда True в том случае, если хотя бы один из операндов выражения будет иметь значение True. Иначе результатом будет False.

Операторы AND и OR можно комбинировать:

((5 3)) OR (5=6) результатом будет True

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

Синтаксис:
NOT Операнд

Оператор NOT выполняет логическое отрицание.

Оператор NOT использует только один операнд.

Операнд Результат
True False
False True

Операторы AND OR NOT можно комбинировать:

((5 3)) OR NOT (5=6) результатом будет True

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

Синтаксис:
Операнд_1 XOR Операнд_2

Оператор XOR выполняет логическое исключение.

Результатом данной операции является значение True, если операнды имеют разные значения, иначе — False.

Операнд_1 Операнд_2 Результат
True True False
True False True
False True True
False False False

((5 3)) OR NOT (5=6) XOR (5=5) результатом будет False

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

Синтаксис:
Операнд_1 EQV Операнд_2

Оператор EQV — это оператор логической эквивалентности.

Результатом данной операции является значение True, если операнды имеют одинаковые значения, иначе — False.

Операнд_1 Операнд_2 Результат
True True True
True False False
False True False
False False True

((5 3)) OR NOT (5=6) EQV (5=5) результатом будет True

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

Синтаксис:
Операнд_1 IMP Операнд_2

Оператор IMP выполняет логическую операцию импликации.

Операнд_1 Операнд_2 Результат
True True True
True False False
False True True
False False True

((5 3)) OR NOT (5=6) IMP (5=5) результатом будет True

Логический оператор IMP наименее интуитивно понятный из всех логических операторов. К счастью, необходимость в его применении возникает довольно редко.

В начало страницы

В начало страницы

Источник

Логические и побитовые операторы в Visual Basic

Логические операторы сравнивают Boolean выражения и возвращают Boolean результат. Операторы And , Or , AndAlso , OrElse и Xor являются двоичными , так как они принимают два операнда, а Not оператор является унарным , так как он принимает один операнд. Некоторые из этих операторов также могут выполнять побитовые логические операции с целочисленными значениями.

Унарный логический оператор

Оператор Not выполняет логическое отрицание Boolean выражения. Он дает логическую противоположность своего операнда. Если выражение имеет True значение , то Not возвращает False значение ; если выражение имеет False значение , то Not возвращает значение True . Это показано в следующем примере.

Двоичные логические операторы

Оператор And выполняет логическое соединение с двумя Boolean выражениями. Если оба выражения имеют значение True , возвращается And True значение . Если хотя бы одно из выражений имеет False значение , то And возвращается False значение .

Оператор Or выполняет логическую дезинъюнкцию или включение двух Boolean выражений. Если любое из выражений имеет True значение , или оба выражения имеют значение True , то Or возвращается значение True . Если ни то или иное выражение не имеет True значения , Or возвращает значение False .

Оператор Xor выполняет логическое исключение для двух Boolean выражений. Если только одно выражение имеет True значение , но не оба, Xor возвращается True значение . Если оба выражения имеют значение True или оба имеют значение False , Xor возвращает значение False .

В следующем примере показаны операторы And , Or и Xor .

логические операции Short-Circuiting

Оператор AndAlso очень похож на And оператор , в том, что он также выполняет логическое соединение с двумя Boolean выражениями. Ключевое различие между ними заключается в том, что AndAlso проявляет короткое замыкание . Если первое выражение в AndAlso выражении имеет False значение , то второе выражение не вычисляется, так как оно не может изменить конечный результат и AndAlso возвращает . False

Аналогичным образом оператор OrElse выполняет укорочение логического дизъюнкции для двух Boolean выражений. Если первое выражение в OrElse выражении имеет True значение , то второе выражение не вычисляется, так как оно не может изменить конечный результат и OrElse возвращает . True

Short-Circuiting Trade-Offs

Сокращение может повысить производительность, не оценивая выражение, которое не может изменить результат логической операции. Однако если это выражение выполняет дополнительные действия, сокращение пропускает эти действия. Например, если выражение включает вызов Function процедуры, эта процедура не вызывается, если выражение сокращено, а любой дополнительный Function код, содержащийся в , не выполняется. Таким образом, функция может выполняться только изредка и может быть проверена неправильно. Или логика программы может зависеть от кода в Function .

В следующем примере показана разница между And , Or и их аналогами с коротким замыканием.

Обратите внимание, что в предыдущем примере некоторый важный код внутри checkIfValid() не выполняется при кратковременном вызове. Первый If оператор вызывает checkIfValid() , хотя 12 > 45 возвращает False , так как And не укорочивает. Второй If оператор не вызывает checkIfValid() , так как, когда 12 > 45 возвращает False , AndAlso укорочает второе выражение. Третий If оператор вызывает checkIfValid() , хотя 12 возвращает True , так как Or не укорочивает. Четвертый If оператор не вызывает checkIfValid() , так как, когда 12 возвращает True , OrElse укорочает второе выражение.

Битовые операции

Побитовые операции вычисляют два целочисленных значения в двоичной форме (основание 2). Они сравнивают биты в соответствующих позициях, а затем присваивают значения на основе сравнения. В следующем примере показан And оператор .

В предыдущем примере задается значение x 1. Это происходит по следующим причинам:

Значения обрабатываются как двоичные:

3 в двоичной форме = 011

5 в двоичной форме = 101

Оператор And сравнивает двоичные представления, одну двоичную позицию (бит) за раз. Если оба бита в заданной позиции имеют значение 1, то 1 помещается в эту позицию в результате. Если любой из битов равен 0, то 0 помещается в эту позицию в результате. В предыдущем примере это работает следующим образом:

011 (3 в двоичной форме)

101 (5 в двоичной форме)

001 (результат в двоичной форме)

Результат обрабатывается как десятичный. Значение 001 является двоичным представлением 1, поэтому x = 1.

Побитовая Or операция аналогична, за исключением того, что биту результата присваивается значение 1, если один или оба сравниваемых бита равны 1. Xor присваивает 1 результирующему биту, если точно один из сравниваемых битов (не оба) равен 1. Not принимает один операнд и инвертирует все биты, включая бит знака, и присваивает это значение результату. Это означает, Not что для подписанных положительных чисел всегда возвращает отрицательное значение, а для отрицательных Not чисел всегда возвращает положительное или нулевое значение.

Операторы AndAlso и OrElse не поддерживают побитовые операции.

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

Источник

3.4 Logical Operators in Excel VBA

In the previous lesson, you used the Conditional Operators. In this lesson, you’ll learn about the Logic Operator.

You can have more than one condition on the same line of your If and ElseIf Statements. To test for more than one condition, you need the Logic Operators. Here’s a table of them:

Only the first three are used regularly. Let’s see how they works. Before doing so, however, there’s one more important variable type we need to discuss — Boolean values.

Boolean Values

You can set up something called a Boolean variable. Boolean variables have only two values: either true or false. You set them up like this:

Dim BooleanFlag As Boolean

Here, we set up a variable called BooleanFlag. Instead of setting the variable to As Integer or As Long we’ve set this one up with As Boolean. The second line puts something in the variable. But notice that that something is a value of True. The only other value we could have used here is False.

You can use your Boolean values like this:

If BooleanFlag = True Then

MsgBox «It’s True»

MsgBox «It’s False»

The first line test if the variable called BooleanFlag is equal to a value of True. If it is, then we display a message. Because there are only two options, we can just have an Else part to test for all other values, as any other value will be False.

You can miss out the = True part, if you like, and just have this:

If BooleanFlag Then

VBA will then take this to mean «If BooleanFlag has a value of True».

With all that in mind, let’s take a look at the Not operator.

Logical Not

The Not operator is used to test if a value or variable is NOT something. We’ll use our BooleanFlag variable from above to demonstrate this concept.

Create a new Sub in your code code window from the previous section. Call it Bool_Test and add the following code:

Dim BooleanFlag As Boolean

If BooleanFlag = True Then

MsgBox «It’s True»

MsgBox «It’s False»

Your coding window will then look like this:

Press F5 to run your code and you should see the first message box appear saying «It’s True».

Now change the first line of your If Statement to this:

If Not BooleanFlag = True Then

We’re using the Logic Operator Not after the word If. Before we added Not, the If Statement read «If BooleanFlag has a value of True». By place the word Not before BooleanFlag we’re now saying, «If BooleanFlag DOES NOT has a value of True». Since BooleanFlag actually does have a value of True then the Else part gets executed.

Run your code again and you should see the second message box appear, saying «It’s False».

Logical And

The And operator test if two or more conditions are true. If, for example, you wanted to check if a number was greater than 20 but less than 30 you can use the And operator to test this condition:

Источник

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!

VBA Boolean data type can only be either TRUE or FALSE – expressed either as “1” (TRUE) or “0” (FALSE).

Boolean values are commonly used with IF statements to verify whether a given condition is met or not, allowing you to build complex logical comparisons.

A blank canvas in the VBA editor is waiting for us, so let’s get started.

Declaring Boolean Variables

First things first, let’s start with declaring Boolean variables so that you can use them in your VBA code.

There are two ways to declare a Boolean variable: 

  • on the module level, meaning the variable can only be used within a given module
  • on the global level, meaning the variable can be used across the entire VBA project

Use the following Dim statement to create a Boolean value on the module level:

Dim BooleanValue As Boolean

On the other hand, copy this public statement to create a global Boolean variable:

Public BooleanValue As Boolean
Declare Boolean variables

Example #1: Using Boolean Variables

Let’s move from theory to practice.

The examples below demonstrate how to use the Boolean data type in VBA. 

Start with creating a new module (Insert > Module). Once there, copy the following code into the VBA editor and click “Run Sub/UserForm” or press F5 to execute it:

Sub Boolean_Vba()
Dim BooleanValue As Boolean
BooleanValue = 50 > 115
MsgBox BooleanValue
End Sub

This simple Sub procedure compares whether 50 is greater than 115 and returns a message box with the corresponding Boolean value based on this simple logical comparison.

Let’s take a closer look at the VBA code to help you adjust accordingly:

  • Dim BooleanValue As Boolean – This line of code creates a new variable named “BooleanValue” and converts it to the Boolean data type.
  • BooleanValue = 50 > 115 – This determines the actual Boolean value of the variable based on the specified logical comparison. If 50 is greater than 115, the value is set to TRUE. If not, the value is set to FALSE.
  • MsgBox BooleanValue – This VBA command creates a message box containing the output.
How to use Boolean variables in VBA

Predictably, VBA returns FALSE since 50 is not greater than 115.

False

Related Article: How to Change The Position And Size Of Excel Charts In VBA

Example #2: Boolean Variables & IF Statements

That was a simple example, so let’s ramp up the difficulty level and break down how you can use the VBA Boolean data type with IF statements.

Imagine you’re overseeing a web development project where the devs are getting paid based on their hourly rate. Your fictitious company allocated 54 hours to the project. 

Armed with this data (and the knowledge of how to apply Boolean values), you can put together a simple IF statement to check if the project runs over budget at any stage of the development process:

Sub Boolean_Vba()
Dim HoursTracked As Integer
Dim HoursPlanned As Integer
Dim Result As Boolean
HoursTracked = 13
HoursPlanned = 54
If HoursTracked > HoursPlanned Then
    Result = True
Else
    Result = False
End If
    MsgBox "Project cost overrun: " & Result
End Sub

The screenshot below breaks down the building blocks of this Sub procedure in greater detail:

Using Boolean variables with IF statements

As a result, VBA will return this message box to help you spot any project cost overrun.

Message box FALSE

Boolean Operators 

In VBA, Boolean operators make it possible for you to work with combinations of Boolean variables, providing you a lot more flexibility.

The four most common Boolean operators in VBA are AND, OR, NOT, and XOR. In this section, we will show you how to use each of them.

The AND Operator

The AND operator connects two or more Boolean expressions and returns TRUE only if all of the conditions are met.

In the example below, the variable “Result” equals TRUE only if both the first condition (50 > 155) and the second condition (50 < 55) are TRUE.

Sub Boolean_Vba()
Dim Result As Boolean
Result = 50 > 155 And 50 < 55 // Use the AND operator to check if both of the conditions are met
MsgBox Result
End Sub

Result: FALSE

The OR Operator

The OR operator returns TRUE if at least one of the conditions is met.

In the same example, the variable “Result” equals TRUE if either the first or second condition is TRUE.

Sub Boolean_Vba()
Dim Result As Boolean
Result = 50 > 155 Or 50 < 55 // Use the OR operator to check if any of the conditions are met
MsgBox Result
End Sub

Result: TRUE

The NOT Operator

The NOT operator turns TRUE into FALSE, and vice versa.

In this example, since 50 is not greater than 155, the VBA editor should return FALSE. However, since the NOT operator is applied, it takes truth to falsity. Another variation is the not-equal-to operator (<>) that works in a similar way.

Sub Boolean_Vba()
Dim Result As Boolean
Result = Not 50 > 155 // Use the NOT operator to reverse the TRUE and FALSE values
MsgBox Result
End Sub

Result: TRUE

The XOR Operator

The XOR operator returns TRUE only if two conditions are not TRUE or FALSE at the same time.

In the example below, the “Result” variable is TRUE because the first condition (50 > 155) is FALSE while the second condition (50 < 55) is TRUE.

Sub Boolean_Vba()
Dim Result As Boolean

Result = 50 > 155 Xor 50 < 55 // Check if BOTH or NEITHER of the conditions are met
MsgBox Result
End Sub

Result: TRUE

Usage Notes

1. The default Boolean value is FALSE.

Sub Boolean_Vba()
Dim Result As Boolean
MsgBox Result
End Sub

Result: FALSE

2. By default, every nonzero number is TRUE.

Sub Boolean_Vba()
Dim Result As Boolean
Result = 15
MsgBox Result
End Sub

Result: TRUE

3. Zero is equal to FALSE.

Sub Boolean_Vba()
Result = 0
MsgBox Result
End Sub

Result: TRUE

4. Boolean values can’t be anything but TRUE or FALSE. If you try to turn a Boolean variable into any other data type, this breaks the code and triggers an error.

Sub Boolean_Vba()
Dim Result As Boolean
Result = “Bird is the word”
MsgBox Result
End Sub

Result: a type-mismatch error – as shown on the screenshot below.

Type-mismatch error

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

Logical Operator And | Logical Operator Or | Logical Operator Not

The three most used logical operators in Excel VBA are: And, Or and Not. As always, we will use easy examples to make things more clear.

Logical Operator And

Place a command button on your worksheet and add the following code lines:

Dim score1 As Integer, score2 As Integer, result As String

score1 = Range(«A1»).Value
score2 = Range(«B1»).Value

If score1 >= 60 And score2 > 1 Then
    result = «pass»
Else
    result = «fail»
End If

Range(«C1»).Value = result

Explanation: if score1 is greater than or equal to 60 and score2 is greater than 1, Excel VBA returns pass, else Excel VBA returns fail.

Result when you click the command button on the sheet:

Excel VBA Logical Operator And

Conclusion: Excel VBA returns fail because score2 is not greater than 1.

Logical Operator Or

Place a command button on your worksheet and add the following code lines:

Dim score1 As Integer, score2 As Integer, result As String

score1 = Range(«A1»).Value
score2 = Range(«B1»).Value

If score1 >= 60 Or score2 > 1 Then
    result = «pass»
Else
    result = «fail»
End If

Range(«C1»).Value = result

Explanation: if score1 is greater than or equal to 60 or score2 is greater than 1, Excel VBA returns pass, else Excel VBA returns fail.

Result when you click the command button on the sheet:

Excel VBA Logical Operator Or

Conclusion: Excel VBA returns pass because score1 is greater than or equal to 60.

Logical Operator Not

Place a command button on your worksheet and add the following code lines:

Dim score1 As Integer, score2 As Integer, result As String

score1 = Range(«A1»).Value
score2 = Range(«B1»).Value

If score1 >= 60 And Not score2 = 1 Then
    result = «pass»
Else
    result = «fail»
End If

Range(«C1»).Value = result

Explanation: if score1 is greater than or equal to 60 and score2 is not equal to 1, Excel VBA returns pass, else Excel VBA returns fail.

Result when you click the command button on the sheet:

Excel VBA Logical Operator Not

Conclusion: Excel VBA returns fail because score2 is equal to 1.

Понравилась статья? Поделить с друзьями:
  • Excel vba bit and
  • Excel vba chart setsourcedata
  • Excel vba bad file name or number
  • Excel vba char string
  • Excel vba background color