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

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

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

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

AND OR NOT XOR EQV IMP

Без логики никуда. Всё программирование это логика. В VBA-Excel так же есть свои логические операторы. Ниже приведена таблица операторов их синтаксис, описание и таблица истинности.

Теперь рассмотрим как они применяются на практике

Оператор AND

Естественно если у нас выражение логическое, то и начинаться оно может с условия Если. Вот например:

          Private Sub CommandButton1_Click()

          If Cells(3, 9) = 1 And Cells(3, 10) = 1 Then

              Cells(3, 11) = 1

          Else

              Cells(3, 11) = 0

          End If

          End Sub

Теперь надо прояснить ситуацию. Если в ячейке Cells(3, 9) и ячейке Cells(3, 10) записана еденица, то в ячейке Cells(3, 11) так же записывается еденица, в противном случае в ячейке Cells(3, 11) прописывается ноль (в примере есть все логические примеры, можете скачать).

Но это не значит, что оно всегда должно начинаться с условия Если то. И не обязательно чтобы в выражении было два входных значения (в данном случае Cells(3, 9) = 1, Cells(3, 10)). Их модет быть столько сколько вы захотите. Например так:

          Private Sub CommandButton1_Click()

          If Cells(3, 9) = 1 And Cells(3, 10) = 1  And Cells(3, 11) = 1 Then

              Cells(3, 12) = 1

          Else

              Cells(3, 12) = 0

          End If

          End Sub

Оператор OR

Тут всё аналогично, начинаем с Если и заканчиваем То. И также входных переменных может быть более двух.

          Private Sub CommandButton2_Click()

          If Cells(8, 9) = 1 Or Cells(8, 10) = 1 Then

              Cells(8, 11) = 1

          Else

              Cells(8, 11) = 0

          End If

          End Sub

Оператор NOT

В случае с НЕ нам достаточно одной входной переменной для получения необходимого результата на выходе.

          Private Sub CommandButton3_Click()

          If Not Cells(13, 9) = 1 Then

              Cells(13, 11) = 1

          Else

              Cells(13, 11) = 0

          End If

          End Sub

В этом случае у нас получается всё в точности противоположно истинне. Если в Cells(13, 9) записана еденица, то получается ноль, в противном случае — еденица (так сказать некий закон подлости).

Оператор XOR

Это что-то вроде оператора OR (или), но тут нет истинности при одинаковых значениях переменных.

          Private Sub CommandButton4_Click()

          If Cells(16, 9) = 1 Xor Cells(16, 10) = 1 Then

              Cells(16, 11) = 1

          Else

              Cells(16, 11) = 0

          End If

          End Sub

Оператор EQV

Данный оператор так же опереирует двумя и более переменными.

          Private Sub CommandButton5_Click()

          If Cells(21, 9) = 1 Eqv Cells(21, 10) = 1 Then

              Cells(21, 11) = 1

          Else

              Cells(21, 11) = 0

          End If

          End Sub

Но если Вы экспериментируете с несколькими переменными, то результат будет совершенно не ожиданный. Вот попробуйте. Это булева алгебра и её не обманешь :-)

Оператор IMP

Данный оператор тоже можно записать через условие Если То.

          Private Sub CommandButton6_Click()

          If Cells(26, 9) = 1 Imp Cells(26, 10) = 1 Then

              Cells(26, 11) = 1

          Else

              Cells(26, 11) = 0

          End If

          End Sub

У кого-то может возникнуть вопрос: А можно ли эти операторы соединить в одном логическом выражении? Конечно можно.

          Sub Primer()

          A = 1

          B = 0

          C = 1

                    If A = 1 And B = 1 Or C = 1 Then

              MsgBox «Истина 1», vbInformation, «Истина»

          Else

              MsgBox «Ложь 0», vbInformation, «Ложь»

          End If

          End Sub

Понравилась статья? Поделить с друзьями:
  • Vba excel линейное программирование
  • Vba excel левый символ
  • Vba excel курсор ячейка
  • Vba excel курсор в ячейку
  • Vba excel кто открыл файл