Show List

Operators and expressions

Operators in VBA are symbols or keywords that perform mathematical, logical, or comparison operations on one or more values, called operands. Expressions in VBA are combinations of operators, operands, and functions that result in a value or a reference to a value.

Here are some examples of operators in VBA:

  • Arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division), \ (integer division), ^ (exponentiation)
vbnet
Copy code
Dim x As Integer Dim y As Integer x = 5 y = 2 Debug.Print x + y 'outputs 7 Debug.Print x / y 'outputs 2.5 Debug.Print x \ y 'outputs 2 Debug.Print x ^ y 'outputs 25
  • Comparison operators: = (equal to), <> (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to)
css
Copy code
Dim a As Integer Dim b As Integer a = 10 b = 5 Debug.Print a = b 'outputs False Debug.Print a <> b 'outputs True Debug.Print a > b 'outputs True Debug.Print a <= b 'outputs False
  • Logical operators: And, Or, Not
vbnet
Copy code
Dim p As Boolean Dim q As Boolean p = True q = False Debug.Print p And q 'outputs False Debug.Print p Or q 'outputs True Debug.Print Not p 'outputs False

To create expressions in VBA, you can combine operators and operands. Here are some examples:

vbnet
Copy code
Dim x As Integer Dim y As Integer x = 5 y = 2 Dim z As Integer z = x + y * 3 ' z = 11 Dim isGreater As Boolean isGreater = x > y ' isGreater = True Dim isPositive As Boolean isPositive = (x > 0) And (y > 0) ' isPositive = True

In the first example, the expression x + y * 3 first multiplies y by 3, and then adds the result to x. In the second example, the expression x > y compares x to y and returns a Boolean value (True or False). In the third example, the expression (x > 0) And (y > 0) combines two comparison expressions using the logical operator And, and returns True only if both expressions are true.


    Leave a Comment


  • captcha text