And or operator in excel vba

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

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 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» – логическая импликация.

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

Содержание

  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. Logical Operators
  15. Logical Operator And
  16. Logical Operator Or
  17. Logical Operator Not
  18. VBA Logical Operators – OR, AND, XOR, NOT, IS, & LIKE
  19. Using the And Logical Operator
  20. Using the Or Logical Operator
  21. Using the Not Logical Operator
  22. Using the Xor Logical Operator
  23. Is Operator
  24. Like Operator
  25. VBA Coding Made Easy
  26. VBA Code Examples Add-in

Логические операторы 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 не поддерживают побитовые операции.

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

Источник

Logical Operators

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

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:

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

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:

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

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:

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

Источник

VBA Logical Operators – OR, AND, XOR, NOT, IS, & LIKE

In this Article

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:

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:

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

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

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:

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:

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

As intA value is 5, the blnResult returns True:

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:

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:

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

As intA value is 5, the blnResult returns True:

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:

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:

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

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

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:

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.”

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 Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Понравилась статья? Поделить с друзьями:
  • And or not syntax excel
  • And or not operators in excel
  • And or in if statement vba excel
  • And or advanced filter excel
  • And operator with if in excel