Arithmetic Operators

Connecting one or two numeric-type variables with arithmetic operators forms an arithmetic expression. Common arithmetic operators include +, -, *, /, etc.

【Excel VBA】

Arithmetic operators in Excel VBA are shown in Table 3-1, where a and b are numeric-type variables.

Table 3-1 Arithmetic Operators in Excel VBA

Below, create two short integer variables, assign values to them, and output the results of various arithmetic operations in the Immediate Window. To demonstrate integer division with negative results, define a third short integer variable and assign it a negative integer. The sample file path is Samples\ch03\Excel VBA\Arithmetic Operators.xlsm.

code.vba
Sub Test()
    Dim intA As Integer
    Dim intB As Integer
    Dim intC As Integer
    intA = 10
    intB = 3
    intC = -3  ' Negative number to demonstrate integer division with negative results
    Debug.Print intA + intB  ' Add two numbers
    Debug.Print intA - intB  ' Subtract two numbers
    Debug.Print intA * intB  ' Multiply two numbers
    Debug.Print intA / intB  ' Divide two numbers
    Debug.Print intA \ intB  ' Integer division
    Debug.Print intA \ intC  ' Integer division with negative result
    Debug.Print intA Mod intB  ' Modulo operation(remainder)
    Debug.Print intA ^ intB  ' Exponentiation
End Sub

Running the procedure outputs the results of each arithmetic operation in the Immediate Window:

code.vba
13
7
30
3.33333333333333
3
-3
1
1000

From this, we can see:

When two numbers cannot be evenly divided, division returns a floating-point number.

Integer division returns the integer part of the quotient.

In Excel VBA, if the result of integer division is negative, the integer part is still taken (truncated toward zero).

【Python】

Arithmetic operators in Python are shown in Table 3-2, where a and b are numeric-type variables.

Table 3-2 Arithmetic Operators in Python

Below, repeat the Excel VBA arithmetic operation examples in Python:

code.python
>>> a = 10
>>> b = 3
>>> c = -3
>>> a + b  # Addition
13
>>> a - b  # Subtraction
7
>>> a * b  # Multiplication
30
>>> a / b  # Division
3.3333333333333335
>>> a // b  # Integer division
3
>>> a // c  # Integer division with negative result
-4
>>> a % b  # Modulo operation
1
>>> a ** b  # Exponentiation
1000

The results of arithmetic operations in Python differ from Excel VBA in only one case: integer division with negative results. In Excel VBA, the result is truncated toward zero (e.g., 10 \ -3 = -3), while in Python, the result is truncated toward negative infinity (e.g., 10 // -3 = -4).