Excel vba bit and

Содержание

  1. Оператор And (Visual Basic)
  2. Синтаксис
  3. Компоненты
  4. Комментарии
  5. Типы данных
  6. Пример 1
  7. Пример 2
  8. Оператор «И»
  9. Синтаксис
  10. Замечания
  11. Пример
  12. См. также
  13. Поддержка и обратная связь
  14. Logical and Bitwise Operators in Visual Basic
  15. Unary Logical Operator
  16. Binary Logical Operators
  17. Short-Circuiting Logical Operations
  18. Short-Circuiting Trade-Offs
  19. Bitwise Operations
  20. Логические и побитовые операторы в Visual Basic
  21. Унарный логический оператор
  22. Двоичные логические операторы
  23. логические операции Short-Circuiting
  24. Short-Circuiting Trade-Offs
  25. Битовые операции

Оператор And (Visual Basic)

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

Синтаксис

Компоненты

result
Обязательный. Произвольное выражение типа Boolean или числового типа. Для логического сравнения result — это логическая комбинация двух Boolean значений. Для побитовых операций — это числовое значение, result представляющее побитовое соединение двух числовых битовых шаблонов.

expression1
Обязательный. Произвольное выражение типа Boolean или числового типа.

expression2
Обязательный. Произвольное выражение типа Boolean или числового типа.

Комментарии

Для логического сравнения имеет значение if и только в том случае, result если оба expression1 значения и expression2 имеют значение True . True В следующей таблице показано, как result определяется.

Если expression1 имеет значение И expression2 это Значение равно result
True True True
True False False
False True False
False False False

В логическом сравнении And оператор всегда вычисляет оба выражения, которые могут включать в себя вызовы процедур. Оператор AndAlso выполняет короткое замыкание, что означает, что если expression1 имеет значение False , то expression2 не вычисляется.

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

Если бит в имеет expression1 значение И бит в expression2 является Бит в result имеет значение
1 1 1
1 0 0
0 1 0
0 0 0

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

Типы данных

Если операнды состоят из одного Boolean выражения и одного числового выражения, Visual Basic преобразует Boolean выражение в числовое значение (–1 для True и 0 для False ) и выполняет побитовую операцию.

Для логического сравнения типом данных результата является Boolean . Для побитового сравнения результирующий тип данных является числовым типом, подходящим для типов expression1 данных и expression2 . См. таблицу «Реляционные и побитовые сравнения» в разделе Типы данных результатов оператора.

Оператор And может быть перегружен, что означает, что класс или структура могут переопределить свое поведение, если операнд имеет тип этого класса или структуры. Если код использует этот оператор для такого класса или структуры, убедитесь, что вы понимаете его переопределенное поведение. Для получения дополнительной информации см. Operator Procedures.

Пример 1

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

В предыдущем примере приводятся результаты True и False соответственно.

Пример 2

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

Предыдущий пример дает результаты 8, 2 и 0 соответственно.

Источник

Оператор «И»

Используется для установления логической связи между двумя выражениями.

Синтаксис

Результат = expression1Иexpression2

Синтаксис оператора And состоит из таких частей:

Part Описание
result Обязательный элемент; любая числовая переменная.
выражение1 Обязательный элемент, любое допустимое выражение.
выражение2 Обязательный элемент, любое допустимое выражение.

Замечания

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

Если expression1 равняется И expression2 равняется result представляет собой
True False False
True Null Null
False True False
False False False
False Null False
Null True Null
Null False False
Null Null Null

Оператор And также выполняет побитовое сравнение аналогично расположенных битов двух числовых выражений и помещает соответствующий бит в result согласно этой таблице:

Если бит в expression1 равняется И бит в expression2 равняется result представляет собой
0 0 0
0 1 0
1 0 0
1 1 1

Пример

В примере показано, как оператор And логически соединяет два выражения.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Logical and Bitwise Operators in Visual Basic

Logical operators compare Boolean expressions and return a Boolean result. The And , Or , AndAlso , OrElse , and Xor operators are binary because they take two operands, while the Not operator is unary because it takes a single operand. Some of these operators can also perform bitwise logical operations on integral values.

Unary Logical Operator

The Not Operator performs logical negation on a Boolean expression. It yields the logical opposite of its operand. If the expression evaluates to True , then Not returns False ; if the expression evaluates to False , then Not returns True . The following example illustrates this.

Binary Logical Operators

The And Operator performs logical conjunction on two Boolean expressions. If both expressions evaluate to True , then And returns True . If at least one of the expressions evaluates to False , then And returns False .

The Or Operator performs logical disjunction or inclusion on two Boolean expressions. If either expression evaluates to True , or both evaluate to True , then Or returns True . If neither expression evaluates to True , Or returns False .

The Xor Operator performs logical exclusion on two Boolean expressions. If exactly one expression evaluates to True , but not both, Xor returns True . If both expressions evaluate to True or both evaluate to False , Xor returns False .

The following example illustrates the And , Or , and Xor operators.

Short-Circuiting Logical Operations

The AndAlso Operator is very similar to the And operator, in that it also performs logical conjunction on two Boolean expressions. The key difference between the two is that AndAlso exhibits short-circuiting behavior. If the first expression in an AndAlso expression evaluates to False , then the second expression is not evaluated because it cannot alter the final result, and AndAlso returns False .

Similarly, the OrElse Operator performs short-circuiting logical disjunction on two Boolean expressions. If the first expression in an OrElse expression evaluates to True , then the second expression is not evaluated because it cannot alter the final result, and OrElse returns True .

Short-Circuiting Trade-Offs

Short-circuiting can improve performance by not evaluating an expression that cannot alter the result of the logical operation. However, if that expression performs additional actions, short-circuiting skips those actions. For example, if the expression includes a call to a Function procedure, that procedure is not called if the expression is short-circuited, and any additional code contained in the Function does not run. Therefore, the function might run only occasionally, and might not be tested correctly. Or the program logic might depend on the code in the Function .

The following example illustrates the difference between And , Or , and their short-circuiting counterparts.

In the preceding example, note that some important code inside checkIfValid() does not run when the call is short-circuited. The first If statement calls checkIfValid() even though 12 > 45 returns False , because And does not short-circuit. The second If statement does not call checkIfValid() , because when 12 > 45 returns False , AndAlso short-circuits the second expression. The third If statement calls checkIfValid() even though 12 returns True , because Or does not short-circuit. The fourth If statement does not call checkIfValid() , because when 12 returns True , OrElse short-circuits the second expression.

Bitwise Operations

Bitwise operations evaluate two integral values in binary (base 2) form. They compare the bits at corresponding positions and then assign values based on the comparison. The following example illustrates the And operator.

The preceding example sets the value of x to 1. This happens for the following reasons:

The values are treated as binary:

3 in binary form = 011

5 in binary form = 101

The And operator compares the binary representations, one binary position (bit) at a time. If both bits at a given position are 1, then a 1 is placed in that position in the result. If either bit is 0, then a 0 is placed in that position in the result. In the preceding example this works out as follows:

011 (3 in binary form)

101 (5 in binary form)

001 (The result, in binary form)

The result is treated as decimal. The value 001 is the binary representation of 1, so x = 1.

The bitwise Or operation is similar, except that a 1 is assigned to the result bit if either or both of the compared bits is 1. Xor assigns a 1 to the result bit if exactly one of the compared bits (not both) is 1. Not takes a single operand and inverts all the bits, including the sign bit, and assigns that value to the result. This means that for signed positive numbers, Not always returns a negative value, and for negative numbers, Not always returns a positive or zero value.

The AndAlso and OrElse operators do not support bitwise operations.

Bitwise operations can be performed on integral types only. Floating-point values must be converted to integral types before bitwise operation can proceed.

Источник

Логические и побитовые операторы в 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 allow you to evaluate one or more expressions and return a logical value. VBA supports six logical operators: And, Or, Not, Eqv, Imp, and Xor. These operators also double as bitwise operators. A bitwise comparison examines each bit position in both expressions and sets or clears the corresponding bit in the result depending upon the operator used. The result of a bitwise operation is a numeric value.

Performs logical conjunction; that is, it only returns True if both expressionl and expression2 evaluate to True. If either expression is False, then the result is False. If either expression is Null, then the result is Null. Its syntax is:

result = expression1 And expression2 For example:

In this case, the code after the If statement is executed only if the value of x is five and the value of y is less than seven.

As a bitwise operator, And returns 1 if the compared bits in both expressions are 1, and returns 0 in all other cases, as shown in the following table:

Bit in expressionl

Bit in expression2

Result

0

0

0

0

1

0

1

0

0

1

1

1

For example, the result of 15 And 179 is 3, as the following binary representation shows:

00000011 = 00001111 And 10110011

Performs logical disjunction; that is, if either expressionl or expression2 evaluates to True, or if both expressionl and expression2 evaluate to True, the result is True. Only if neither expression is True does the Or operation return False. If either expression is Null, then the result is also Null. The syntax for the Or operator is:

608 Appendix C- Operators result = expressionl Or expression2 For example:

In this case, the code after the If statement is executed if the value of x is five or if the value of y is less than seven.

As a bitwise operator, Or is the converse of And. Or returns 0 if the compared bits in both expressions are 0, and returns 1 in all other cases, as shown in the following table:

Bit in expressionl

Bit in expression2

Result

0

0

0

0

1

1

1

0

1

1

1

1

For example, the result of 15 Or 179 is 191, as the following binary representation shows:

10111111 = 00001111 Or 10110011

Performs logical negation on a single expression; that is, if the expression is True, the Not operator causes it to become False, while if it is False, the operator causes its value to become True. If the expression is Null, though, the result of using the Not operator is still a Null. Its syntax is:

result = Not expression1

For example:

If Not IsNumeric(x) Then

In this example, the code following the If statement is executed if IsNumeric returns False, indicating that x isn’t a value capable of being represented by a number.

As a bitwise operator, Not simply reverses the value of the bit, as shown in the following table:

expressionl

Result

0

1

1

0

For example, the result of Not 16 is 239, as the following binary representation shows:

Not 00010000 = 11101111

Performs logical equivalence; that is, it determines whether the value of two expressions is the same. Eqv returns True when both expressions evaluate to

Logical and Bitwise Operators 609

True or both expressions evaluate to False, but it returns False if either expression evaluates to True while the other evaluates to False. Its syntax is:

result = expressionl Eqv expression2

As a bitwise operator. Eqv returns 1 if the compared bits in both expressions are the same, and it returns 0 if they are different, as shown in the following table:

Bit in expressionl

Bit in expression2

Result

0

0

1

0

1

0

1

0

0

1

1

1

For example, the result of 15 Eqv 179 is 67, as the following binary representation shows:

01000011 = 00001111 Eqv 10110011

Performs logical implication, as shown in the following table:

expression1

expression2

result

True

True

True

True

False

False

True

Null

Null

False

True

True

False

False

True

False

Null

True

Null

True

True

Null

False

Null

Null

Null

result = expressionl Imp expression2

As a bitwise operator, Imp returns 1 if the compared bits in both expressions are the same or if expressionl is 1; it returns 0 if the two bits are different and the bit in expressionl is 1, as shown in the following table:

Bit in expression1

Bit in expression2

Result

0

0

1

0

1

1

1

0

0

1

1

1

610 Appendix C- Operators

For example, the result of 15 Imp 179 is 243, as the following binary representation shows:

llll00ll = 0000llll Imp l0ll00ll

Performs logical exclusion, which is the converse of Eqv; that is, Xor (an abbreviation for exclusive OR) determines whether two expressions are different. When both expressions are either True or False, then the result is False. If only one expression is True, the result is True. If either expression is Null, the result is also Null. Its syntax is:

result = expressionl Xor expression2

As a bitwise operator, Xor returns 1 if the bits being compared are different, and returns 0 if they are the same, as shown in the following table:

Bit in expressionl

Bit in expression2

Result

0

0

0

0

1

1

1

0

1

1

1

0

For example, the result of 15 Xor 179 is 188, as the following binary representation shows:

l0llll00 = 0000llll Imp l0ll00ll

Continue reading here: Visual Basic Deletefile

Was this article helpful?

This is an entirely mathematical approach to working with IPv4 addresses in VBA (Excel specifically).

The first three functions are serving a strictly supporting role.

Support #1:

Public Function RoundDouble(ByVal Number As Double, ByVal Places As Long) As Double
    On Error GoTo Err_RoundDouble

    Dim i As Long
    Dim j As Long

    i = 0
    j = 0

    While Number < -(2 ^ 14)
        Number = Number + (2 ^ 14)
        i = i - 1
    Wend
    While Number > (2 ^ 14)
        Number = Number - (2 ^ 14)
        i = i + 1
    Wend
    While Number < -(2 ^ 5)
        Number = Number + (2 ^ 5)
        j = j - 1
    Wend
    While Number > (2 ^ 5)
        Number = Number - (2 ^ 5)
        j = j + 1
    Wend

    RoundDouble = Round(Number, Places) + (i * (2 ^ 14)) + (j * (2 ^ 5))

Exit_RoundDouble:
    Exit Function

Err_RoundDouble:
    MsgBox Err.Description
    Resume Exit_RoundDouble

End Function

Support #2:

Public Function RoundDownDouble(ByVal Number As Double, ByVal Places As Long) As Double
    On Error GoTo Err_RoundDownDouble
    Dim i As Double

    i = RoundDouble(Number, Places)

    If Number < 0 Then
        If i < Number Then
            RoundDownDouble = i + (10 ^ -Places)
        Else
            RoundDownDouble = i
        End If
    Else
        If i > Number Then
            RoundDownDouble = i - (10 ^ -Places)
        Else
            RoundDownDouble = i
        End If
    End If

Exit_RoundDownDouble:
    Exit Function

Err_RoundDownDouble:
    MsgBox Err.Description
    Resume Exit_RoundDownDouble

End Function

Support #3

Public Function ModDouble(ByVal Number As Double, ByVal Divisor As Double) As Double
    On Error GoTo Err_ModDouble
    Dim rndNumber As Double
    Dim rndDivisor As Double
    Dim intermediate As Double

    rndNumber = RoundDownDouble(Number, 0)
    rndDivisor = RoundDownDouble(Divisor, 0)

    intermediate = rndNumber / rndDivisor
    ModDouble = (intermediate - RoundDownDouble(intermediate, 0)) * rndDivisor

Exit_ModDouble:
    Exit Function

Err_ModDouble:
    MsgBox Err.Description
    Resume Exit_ModDouble

End Function

This first function will convert a Double back into an IP address.

Public Function NUMtoIP(ByVal Number As Double) As String
    On Error GoTo Err_NUMtoIP

    Dim intIPa As Double
    Dim intIPb As Double
    Dim intIPc As Double
    Dim intIPd As Double

    If Number < 0 Then Number = Number * -1

    intIPa = RoundDownDouble(ModDouble(Number, (2 ^ 32)) / (2 ^ 24), 0)
    intIPb = RoundDownDouble(ModDouble(Number, (2 ^ 24)) / (2 ^ 16), 0)
    intIPc = RoundDownDouble(ModDouble(Number, (2 ^ 16)) / (2 ^ 8), 0)
    intIPd = ModDouble(Number, (2 ^ 8))

    NUMtoIP = intIPa & "." & intIPb & "." & intIPc & "." & intIPd

Exit_NUMtoIP:
    Exit Function

Err_NUMtoIP:
    MsgBox Err.Description
    Resume Exit_NUMtoIP

End Function

This second function is strictly to convert from IPv4 dotted octet format to a Double.

Public Function IPtoNUM(ByVal IP_String As String) As Double
    On Error GoTo Err_IPtoNUM
    Dim intIPa As Integer
    Dim intIPb As Integer
    Dim intIPc As Integer
    Dim intIPd As Integer
    Dim DotLoc1 As Integer
    Dim DotLoc2 As Integer
    Dim DotLoc3 As Integer
    Dim DotLoc4 As Integer

    DotLoc1 = InStr(1, IP_String, ".", vbTextCompare)
    DotLoc2 = InStr(DotLoc1 + 1, IP_String, ".", vbTextCompare)
    DotLoc3 = InStr(DotLoc2 + 1, IP_String, ".", vbTextCompare)
    DotLoc4 = InStr(DotLoc3 + 1, IP_String, ".", vbTextCompare)

    If DotLoc1 > 1 And DotLoc2 > DotLoc1 + 1 And _
     DotLoc3 > DotLoc2 + 1 And DotLoc4 = 0 Then

        intIPa = CInt(Mid(IP_String, 1, DotLoc1))
        intIPb = CInt(Mid(IP_String, DotLoc1 + 1, DotLoc2 - DotLoc1))
        intIPc = CInt(Mid(IP_String, DotLoc2 + 1, DotLoc3 - DotLoc2))
        intIPd = CInt(Mid(IP_String, DotLoc3 + 1, 3))

        If intIPa <= 255 And intIPa >= 0 And intIPb <= 255 And intIPb >= 0 And _
         intIPc <= 255 And intIPc >= 0 And intIPd <= 255 And intIPd >= 0 Then

            IPtoNUM = (intIPa * (2 ^ 24)) + (intIPb * (2 ^ 16)) + _
                      (intIPc * (2 ^ 8)) + intIPd

        Else

            IPtoNUM = 0

        End If
    Else
        IPtoNUM = 0
    End If

Exit_IPtoNUM:
    Exit Function

Err_IPtoNUM:
    MsgBox Err.Description
    Resume Exit_IPtoNUM


End Function

Next we have the conversion from an IPv4 address to it’s bitmask representation (assuming that the source entry is a string containing only the dotted octet format of the subnet mask).

Public Function IPtoBitMask(ByVal strIP_Address As String) As Integer
    On Error GoTo Err_IPtoBitMask

    IPtoBitMask = (32 - Application.WorksheetFunction.Log((2 ^ 32 - IPtoNUM(strIP_Address)), 2))

Exit_IPtoBitMask:
    Exit Function

Err_IPtoBitMask:
    MsgBox Err.Description
    Resume Exit_IPtoBitMask

End Function

This last one is to convert a bitmask back into dotted octet format.

Public Function BitMasktoIP(ByVal intBit_Mask As Integer) As String
    On Error GoTo Err_BitMasktoIP

    BitMasktoIP = NUMtoIP((2 ^ 32) - (2 ^ (32 - intBit_Mask)))

Exit_BitMasktoIP:
    Exit Function

Err_BitMasktoIP:
    MsgBox Err.Description
    Resume Exit_BitMasktoIP

End Function

Edited to remove leftover debugging code (it’s been working for me so long, that I had entirely forgotten about it).

As an aside, it is faster to perform mathematical operations on a computer than it is to work with a string.

The NOT, AND, OR and XOR functions in Microsoft Excel are logical functions and not bitwise functions. What this means is that they only return TRUE or FALSE based on the input expressions given.

In Microsoft Excel 2013, Microsoft has released new functions that work on the bit level: BITNOT, BITAND, BITOR and BITNOT. But these functions are not available in earlier versions of Excel (eg. Excel 2007 or Excel 2010).

If we want to have similar functionality in Excel 2010 or earlier, we will need to implement the functions in Excel VBA instead. To do that, open the Visual Basic editor by pressing ALT-F11. Once you are in the Excel VBA, create a new Module from the Insert Menu and copy the following lines of Visual Basic code to the Module.

Public Function BITWISE_XOR(x As Long, y As Long)
    BITWISE_XOR = x Xor y
End Function

Public Function BITWISE_NOT(x As Long)
    BITWISE_NOT = Not x
End Function

Public Function BITWISE_AND(x As Long, y As Long)
    BITWISE_AND = x And y
End Function

Public Function BITWISE_OR(x As Long, y As Long)
    BITWISE_OR = x Or y
End Function

Save the VBA Module and exit from the editor. Then make sure that you save the original file as Excel Macro-Enabled Workbook and not as just an Excel Workbook, else the above VBA module will not be saved.

excel-bitwise-xor

Now, we are able to use the new custom Excel bitwise functions. The screenshot above shows an example on how the BITWISE_XOR function can be used.

ibrahim = {
interested_in(unix, linux, android, open_source, reverse_engineering);
coding(c, shell, php, python, java, javascript, nodejs, react);
plays_on(xbox, ps4);
linux_desktop_user(true);
}

VBA AND

Excel VBA AND Function

VBA AND function checks the provided statement whether it is true or false. AND function also evaluates the conditions with one another. If both the statements are true, the expression becomes true. Commonly this is associated with different decision-making loops to express the conditions. Comparing to all other logical operators AND returns true only if all the supplied conditions are true.

When you want to evaluate more than one expression and take decisions according to that then logical operators are the best option. AND operators connect two or more conditions together and evaluate the entire statement as a single expression. If all the statement is true, then the total expression returns true. If any expression evaluates false, then the entire statement will return false.

How to Use the AND Function in Excel VBA?

The logical AND can be used along with comparison operators, arithmetic operators, and text, etc. Any number of statements can be connected using AND. The logic behind AND operator is as follows.

Condition 1 Condition 2 Result
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE

When more than two conditions are used, each condition should return true to make the entire expression true.

Syntax of VBA AND:

Format of VBA AND is expressed as,

[Condition1] And [Condition 2] And [Condition 3] And………. [Condition n]

  • [Condition 1 to Condition n] can be a statement expressed using text and any operators.

You can download this VBA AND Excel Template here – VBA AND Excel Template

Example #1

In this example, you can learn how to use AND function along with comparison operators. You have the marks scored by a student in a different subject. If the total comes more than 80 and 22 marks on the main subject the student got passed in the exam else fail. For this, follow the below steps:

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Create a function named result in VBA to do the calculation and find the total mark of all subjects.

Code:

Private Sub result()

End Sub

VBA AND Example1-2

Step 3: Give the marks for different subjects. a, b, c, d are different subjects and the marks scored for each subject is as below. a is the main subject and s is the sum of all subjects a, b, c, d.

Code:

Private Sub result()

a = 25
b = 20
c = 20
d = 20
s = a + b + c + d

End Sub

VBA AND Example1-3

Step 4: Now express the conditions as two statements and connect with AND function. IF …Else loop is used to execute the two different results according to the evaluation of the expression.

Code:

Private Sub result()

a = 25
b = 20
c = 20
d = 20
s = a + b + c + d
If s > 80 And a > 22 Then
Else
End If

End Sub

VBA AND Example1-4

Step 5: Set the message to show according to the condition valuation. Where both conditions are true the entire expression becomes true and the true section of IF… Else loop will execute. Else the control will move to the false section.

Code:

Private Sub result()

a = 25
b = 20
c = 20
d = 20
s = a + b + c + d
If s > 80 And a > 22 Then
MsgBox "Student got passed the exam"
Else
MsgBox "Failed"
End If

End Sub

IF-Else loop Example1-5

So if the sum is greater than 80 and the mark for the main subject ‘a’ is greater than 22 then the message “student got passed the exam” will show else fail is the result.

Step 6: Run this code by hitting the F5 or Run button which is placed on the topmost ribbon of VBE. The marks scored in the main subject is greater than 22 and the sum of all subject is greater than 80.

VBA AND Example1-6

Here both the condition is true so the entire logical AND expression become true and the message in true section of IF… Else loop will be executed.

Example #2

There is no limit for giving the number of conditions with VBA AND. You can use ‘n’ number of conditions and VBA AND operator within a single expression. From an employee database, you have the attendance of a particular employee. You have the number of days that he was present in the office for the past 5 months. If the employee has 25 or more than 25 days’ attendance for every month, he is eligible for a bonus. For this, follow the below steps:

Step 1: In the same module let us start with another subprocedure.

Code:

Private Sub bonus()

End Sub

VBA AND Example2-1

Step 2: To check the above conditions, start with a function ‘bonus’ and attendance for each month.

Private Sub bonus()

jan = 25
feb = 24
mar = 25
apr = 25

End Sub

VBA AND Example2-2

Step 3: Now, check each month’s attendance to confirm whether it is greater than or equal to 25. So multiple ‘AND’ operators are used to check the condition. The value of the entire expression is assigned to ‘b’ which returns a Boolean value.

Code:

Private Sub bonus()

jan = 25
feb = 24
mar = 25
apr = 25
b = jan >= 25 And feb >= 25 And mar >= 25 And apr >= 25

End Sub

VBA AND Example2-3

Step 4: According to this Boolean value, you can a loop. The value of ‘b’ should be true or false.

Code:

Private Sub bonus()

jan = 25
feb = 24
mar = 25
apr = 25
b = jan >= 25 And feb >= 25 And mar >= 25 And apr >= 25
If b = "True" Then
MsgBox " Employee eligible for bonus"
End If
If b = "False" Then
MsgBox "Employee does not meet the criteria"
End If

End Sub

Loop Example2-4

Two IF loops are set to execute according to the Boolean value of b. Here apart from Feb all month’s attendance is greater than or equal to 25. But even a single statement evaluates false the entire expression becomes false. ‘AND’ function returns false and the value of ‘b’ becomes false.

Step 5: So the second IF loop will be executed and the message within this will display as “Employee does not meet the criteria.

VBA AND Example2-5

Here expression is evaluated as follows. First and last two conditions are true and the second condition is false. So while evaluating the entire expression, it becomes false.

Example #3

VBA AND to Evaluate User Credentials. Create a sign-in form using forms and controls in VBA which is available in the code window. For this, follow the below steps:

Step 1: Now Insert a new UserForm inside Visual Basic Editor (VBE). Click on Insert tab > select UserForm. Design a window using Toolbox with a user name, password and a sign-in button.

UserForm Example3-1

Step 2: Click the Sign-in button using the AND operator. Once the credentials are provided check the text value comes to both username and password textboxes, Textbox1 and Textbox 2. If the username is “Tutorial” and password is “Edcba1A45” then the credentials are correct and the user will be able to sign in and a welcome message will be displayed. Else error message is displayed.

Code:

Private Sub CommandButton1_Click()

If (TextBox1.Text = "Tutorial") And (TextBox2.Text = "Edcba1A45") Then
MsgBox "Welcome to your account'"
Else
MsgBox "Oops username or password is incorrect"
End If

End Sub

VBA AND Example3-2

Step 3: Both conditions are expressed in an IF loop. AND operator evaluates these both conditions. Run the form using the run button and give username and password in the text field.

User Credentials Example3-3

User Credentials3-3

Since the username is “Tutorial” and password is “Edcba1A45” the AND operator returns a true and true block of IF loop will execute.

Things to Remember

  • The logical AND function will always return a Boolean value true or false
  • Commonly use with decision-making loops.
  • Helps to compare ‘n’ number of expressions at a time by connecting with logical AND
  • The entire statement returns true only if each statement is true.

Recommended Articles

This is a guide to the VBA AND. Here we discuss how to Use the AND Function in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA PasteSpecial
  2. VBA Dynamic Array
  3. VBA ReDim Array
  4. VBA SubString

замечания

Операторы оцениваются в следующем порядке:

  • Математические операторы
  • Побитовые операторы
  • Операторы конкатенации
  • Операторы сравнения
  • Логические операторы

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

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

Перечислено в порядке очередности:

знак название Описание
^ Возведение Верните результат подъема левого операнда в силу правого операнда. Обратите внимание, что значение, возвращаемое экспоненциацией, всегда равно Double , независимо от того, какие типы значений делятся. Любое принуждение результата к переменному типу происходит после выполнения вычисления.
/ Раздел 1 Возвращает результат деления левого операнда на правый операнд. Обратите внимание, что значение, возвращаемое делением, всегда равно Double , независимо от того, какие типы значений делятся. Любое принуждение результата к переменному типу происходит после выполнения вычисления.
* Умножение 1 Возвращает произведение двух операндов.
Целостный отдел Возвращает целочисленный результат деления левого операнда правым операндом после округления обеих сторон с округлением .5. Любое остальное подразделение игнорируется. Если правый операнд (делитель) равен 0 , это приведет к ошибке времени выполнения 11: деление на ноль. Обратите внимание, что это происходит после округления — выражения, такие как 3 0.4 , также приводят к делению на нулевую ошибку.
Mod Модульное Возвращает целочисленный остаток деления левого операнда на правый операнд. Операнд с каждой стороны округляется до целого числа до деления с округлением .5. Например, и 8.6 Mod 3 и 12 Mod 2.6 приводят к 0 . Если правый операнд (делитель) равен 0 , это приведет к ошибке времени выполнения 11: деление на ноль. Обратите внимание, что это выполняется после округления — выражения, такие как 3 Mod 0.4 , также приводят к делению на нулевую ошибку.
- Вычитание 2 Возвращает результат вычитания правого операнда из левого операнда.
+ Добавление 2 Возвращает сумму из двух операндов. Обратите внимание, что этот токен также рассматривается как оператор конкатенации, когда он применяется к String . См. Операторы конкатенации .

1 Умножение и деление рассматриваются как имеющие тот же приоритет.

2 Сложение и вычитание рассматриваются как имеющие тот же приоритет.

Операторы конкатенации

VBA поддерживает 2 разных оператора конкатенации + и & и выполняет одну и ту же функцию при использовании со String типами — правая String добавляется к концу левой String .

Если оператор & используется с переменным типом, отличным от String , он неявно передается в String перед конкатенацией.

Обратите внимание, что оператор + конкатенации является перегрузкой оператора + сложения. Поведение + определяется переменными типами операндов и приоритетом типов операторов. Если оба операнда напечатаны как String или Variant с Variant String , они объединяются:

Public Sub Example()
    Dim left As String
    Dim right As String
    
    left = "5"
    right = "5"
    
    Debug.Print left + right    'Prints "55"
End Sub

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

Public Sub Example()
    Dim left As Variant
    Dim right As String
    
    left = 5
    right = "5"
    
    Debug.Print left + right    'Prints 10
End Sub

Такое поведение может привести к тонким, трудно отлаживающим ошибкам, особенно если используются типы Variant , поэтому для конкатенации обычно следует использовать оператор & .

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

знак название Описание
= Равно Возвращает True если левый и правый операнды равны. Обратите внимание, что это перегрузка оператора присваивания.
<> Не равен Возвращает True если левый и правый операнды не равны.
> Лучше чем Возвращает True если левый операнд больше правого операнда.
< Меньше, чем Возвращает True если левый операнд меньше правого операнда.
>= Больше или равно Возвращает True если если левый операнд больше или равен правому операнду.
<= Меньше или равно Возвращает True если левый операнд меньше или равен правому операнду.
Is Справочный капитал Возвращает значение True если ссылка на левый объект — это тот же экземпляр, что и ссылка на правый объект. Он также может использоваться с Nothing (ссылка на нулевой объект) с обеих сторон. Примечание. Оператор Is попытается принудить оба операнда к Object перед выполнением сравнения. Если какая-либо сторона является примитивным типом или Variant , который не содержит объект (либо не-объектный подтип, либо vtEmpty ), сравнение приведет к ошибке времени выполнения 424 — «Требуется объект». Если любой операнд принадлежит другому интерфейсу одного и того же объекта, сравнение вернет True . Если вам нужно проверить справедливость как экземпляра, так и интерфейса, ObjPtr(left) = ObjPtr(right) используйте ObjPtr(left) = ObjPtr(right) .

Заметки

Синтаксис VBA позволяет «цепочки» операторов сравнения, но в целом эти конструкции следует избегать. Сравнение всегда выполняется слева направо только на 2 операндах за раз, и каждое сравнение приводит к Boolean . Например, выражение …

a = 2: b = 1: c = 0
expr = a > b > c

… может быть прочитан в некоторых контекстах как проверка того, является ли b между a и c . В VBA это оценивается следующим образом:

a = 2: b = 1: c = 0
expr = a > b > c
expr = (2 > 1) > 0
expr = True > 0
expr = -1 > 0 'CInt(True) = -1
expr = False

Любой оператор сравнения, кроме Is использоваться с Object в качестве операнда будет выполняться на возвращаемом значении Object «s члена по умолчанию . Если объект не имеет члена по умолчанию, сравнение приведет к ошибке времени выполнения 438 — «Объект не поддерживает его свойство или метод».

Если Object не инициализирован, сравнение приведет к ошибке времени выполнения 91 — «Объектная переменная или С заблокированной переменной блока».

Если литерал Nothing используется с любым оператором сравнения, отличным от Is , это приведет к ошибке компиляции — «Недопустимое использование объекта».

Если Object по умолчанию Object является другой Object , VBA будет постоянно вызывать элемент по умолчанию каждого последующего возвращаемого значения до тех пор, пока не будет возвращен примитивный тип или не будет поднята ошибка. Например, предположим, что у SomeClass есть член по умолчанию Value , который является экземпляром ChildClass с членом ChildValue по ChildValue . Сравнение…

Set x = New SomeClass
Debug.Print x > 42

… будет оцениваться как:

Set x = New SomeClass
Debug.Print x.Value.ChildValue > 42

Если либо операнд является числовым, а другой операндом является String или Variant подтипа String , будет выполнено числовое сравнение. В этом случае, если String не может быть отнесено к числу, результатом сравнения будет ошибка времени выполнения 13 — «Несоответствие типа».

Если оба операнда представляют собой String или Variant подтипа String , сравнение строк будет выполняться на основе параметра сравнения параметров модуля кода. Эти сравнения выполняются по характеру по характеру. Обратите внимание, что символьное представление String содержащей число, не совпадает с сопоставлением числовых значений:

Public Sub Example()
    Dim left As Variant
    Dim right As Variant
    
    left = "42"
    right = "5"
    Debug.Print left > right              'Prints False
    Debug.Print Val(left) > Val(right)    'Prints True
End Sub

По этой причине убедитесь, что переменные String или Variant передаются в числа перед выполнением численных сравнений неравенства.

Если один из операндов — это Date , то числовое сравнение по базовому двойному значению будет выполняться, если другой операнд является числовым или может быть преобразован в числовой тип.

Если другой операнд представляет собой String или Variant подтипа String который может быть перенесен в Date с использованием текущего языкового стандарта, String будет передана в Date . Если он не может быть применен к Date в текущей локали, результатом сравнения будет ошибка времени выполнения 13 — «Несоответствие типа».


Следует соблюдать осторожность при сравнении значений Double или Single и Booleans . В отличие от других числовых типов ненулевые значения нельзя считать True из-за поведения VBA в продвижении типа данных сравнения с использованием числа с плавающей точкой в Double :

Public Sub Example()
    Dim Test As Double
    
    Test = 42        Debug.Print CBool(Test)             'Prints True.
    'True is promoted to Double - Test is not cast to Boolean
    Debug.Print Test = True             'Prints False
    
    'With explicit casts:
    Debug.Print CBool(Test) = True      'Prints True
    Debug.Print CDbl(-1) = CDbl(True)   'Prints True
End Sub

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

Все логические операторы в VBA можно рассматривать как «переопределения» побитовых операторов с тем же именем. Технически они всегда рассматриваются как побитовые операторы. Все операторы сравнения в VBA возвращают логическое значение , которое всегда не будет содержать ни одного из его битов ( False ) или всех его битов ( True ). Но он будет обрабатывать значение с любым битом, установленным как True . Это означает, что результат приведения побитового результата выражения в Boolean (см. Операторы сравнения) всегда будет таким же, как рассматривать его как логическое выражение.

Присвоение результата выражения с использованием одного из этих операторов даст побитовый результат. Обратите внимание, что в таблицах истинности ниже 0 эквивалентно False и 1 эквивалентно True .


And

Возвращает True если выражения с обеих сторон оцениваются как True .

Левый Операнд Правый операнд Результат
0 0 0
0 1 0
1 0 0
1 1 1

Or

Возвращает значение True если любая из сторон выражения имеет значение True .

Левый Операнд Правый операнд Результат
0 0 0
0 1 1
1 0 1
1 1 1

Not

Возвращает True если выражение оценивается как False и False если выражение оценивается как True .

Правый операнд Результат
0 1
1 0

Not единственный операнд без левого операнда. Редактор Visual Basic автоматически упростит выражения с помощью аргумента левой руки. Если вы наберете …

Debug.Print x Not y

… VBE изменит линию на:

Debug.Print Not x

Аналогичные упрощения будут сделаны для любого выражения, содержащего левый операнд (включая выражения) для Not .


Xor

Также известен как «эксклюзивный» или «эксклюзивный». Возвращает значение True если оба выражения оцениваются по разным результатам.

Левый Операнд Правый операнд Результат
0 0 0
0 1 1
1 0 1
1 1 0

Заметим, что хотя оператор Xor можно использовать как логический оператор, нет абсолютно никаких оснований для этого, поскольку он дает тот же результат, что и оператор сравнения <> .


Eqv

Также известен как «эквивалентность». Возвращает True когда оба выражения оцениваются с одним и тем же результатом.

Левый Операнд Правый операнд Результат
0 0 1
0 1 0
1 0 0
1 1 1

Обратите внимание, что функция Eqv очень редко используется, поскольку x Eqv y эквивалентно гораздо более читаемому Not (x Xor y) .


Imp

Также известен как «импликация». Возвращает True если оба операнда одинаковы или второй операнд имеет значение True .

Левый Операнд Правый операнд Результат
0 0 1
0 1 1
1 0 0
1 1 1

Обратите внимание, что функция Imp очень редко используется. Хорошим правилом является то, что если вы не можете объяснить, что это значит, вы должны использовать другую конструкцию.

Понравилась статья? Поделить с друзьями:
  • Excel vba bad file name or number
  • Excel vba char string
  • Excel vba background color
  • Excel vba change all cells
  • Excel vba autofilter criteria not