Читать книгу Excel 2019 Power Programming with VBA - Michael Alexander, Dick Kusleika - Страница 169

CAUTION

Оглавление

The negation operator (a minus sign) is handled differently in VBA. In Excel, the following formula returns 25:

=-5^2

In VBA, x equals –25 after this statement is executed.

x = -5 ^ 2

VBA performs the exponentiation operation first and then applies the negation operator. The following statement returns 25:

x = (-5) ^ 2

In the statement that follows, x is assigned the value 10 because the multiplication operator has a higher precedence than the addition operator:

x = 4 + 3 * 2

To avoid ambiguity, you may prefer to write the statement as follows:

x = 4 + (3 * 2)

In addition, VBA provides a full set of logical operators, shown in Table 3.4. For complete details on these operators (including examples), use the VBA Help system.

TABLE 3.4 VBA Logical Operators

Operator What It Does
Not Performs a logical negation on an expression
And Performs a logical conjunction on two expressions
Or Performs a logical disjunction on two expressions
Xor Performs a logical exclusion on two expressions
Eqv Performs a logical equivalence on two expressions
Imp Performs a logical implication on two expressions

The following instruction uses the Not operator to toggle the gridline display in the active window. The DisplayGridlines property takes a value of either True or False. Therefore, using the Not operator changes False to True and True to False.

ActiveWindow.DisplayGridlines = Not ActiveWindow.DisplayGridlines

The following expression performs a logical And operation. The MsgBox statement displays True only when Sheet1 is the active sheet and the active cell is in Row 1. If either or both of these conditions aren't true, the MsgBox statement displays False.

MsgBox ActiveSheet.Name = "Sheet1" And ActiveCell.Row = 1

The following expression performs a logical Or operation. The MsgBox statement displays True when either Sheet1 or Sheet2 is the active sheet.

MsgBox ActiveSheet.Name = "Sheet1" Or ActiveSheet.Name = "Sheet2"

Excel 2019 Power Programming with VBA

Подняться наверх