Арифметические (математические) операторы, использующиеся в VBA Excel. Их предназначение, особенности вычислений, приоритет в выражениях.
Обзор арифметических операторов
Операторы | Описание |
---|---|
Оператор «+» | Сложение двух чисел или объединение двух строк (для объединения строк предпочтительнее использовать оператор «&») |
Оператор «-» | Вычитание (определение разности двух чисел) или отрицание (отражение отрицательного значения числового выражения: -15, -a) |
Оператор «*» | Умножение двух чисел |
Оператор «/» | Деление двух чисел (деление на 0 приводит к ошибке) |
Оператор «^» | Возведение числа в степень |
Оператор «» | Целочисленное деление |
Оператор «Mod» | Возвращает остаток от деления двух чисел |
Особенности операторов «» и «Mod»
Перед вычислением целочисленного результата или остатка от деления двух чисел делимое и делитель округляются. Причем, используется бухгалтерское округление:
- -3.5 => -4
- -2.5 => -2
- -1.5 => -2
- -0.5 => 0
- 0.5 => 0
- 1.5 => 2
- 2.5 => 2
- 3.5 => 4
Следующие строки вызовут ошибку «Division by zero» («Деление на ноль»):
a = 3 Mod 0.5 a = 3 (2 – 2.5) |
Чтобы избежать ошибок, когда требуется общепринятое математическое округление, округляйте делитель и делимое с помощью оператора WorksheetFunction.Round.
Приоритет арифметических операторов
Приоритет определяет очередность выполнения математических операторов в одном выражении. Очередность выполнения арифметических операторов в VBA Excel следующая:
- «^» – возведение в степень;
- «—» – отрицание;
- «*» и «/» – умножение и деление;1
- «» – целочисленное деление;
- «Mod» – остаток от деления двух чисел;
- «+» и «—» – сложение и вычитание.2
1 Если умножение и деление выполняются в одном выражении, то каждая такая операция выполняется слева направо в порядке их следования.
2 Если сложение и вычитание выполняются в одном выражении, то каждая такая операция выполняется слева направо в порядке их следования.
Для переопределения приоритета выполнения математических операторов в VBA Excel используются круглые скобки. Сначала выполняются арифметические операторы внутри скобок, затем — операторы вне скобок. Внутри скобок приоритет операторов сохраняется.
a = 3 ^ 2 + 1 ‘a = 10 a = 3 ^ (2 + 1) ‘a = 27 a = 3 ^ (2 + 1 * –2) ‘a = 1 |
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid | |||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Learn more about: Mod operator (Visual Basic) |
Mod Operator |
04/24/2018 |
vb.Mod |
|
6ff7e40e-cec8-4c77-bff6-8ddd2791c25b |
Mod operator (Visual Basic)
Divides two numbers and returns only the remainder.
Syntax
result = number1 Mod number2
Parts
result
Required. Any numeric variable or property.
number1
Required. Any numeric expression.
number2
Required. Any numeric expression.
Supported types
All numeric types. This includes the unsigned and floating-point types and Decimal
.
Result
The result is the remainder after number1
is divided by number2
. For example, the expression 14 Mod 4
evaluates to 2.
[!NOTE]
There is a difference between remainder and modulus in mathematics, with different results for negative numbers. TheMod
operator in Visual Basic, the .NET Frameworkop_Modulus
operator, and the underlying rem IL instruction all perform a remainder operation.
The result of a Mod
operation retains the sign of the dividend, number1
, and so it may be positive or negative. The result is always in the range (-number2
, number2
), exclusive. For example:
Public Module Example Public Sub Main() Console.WriteLine($" 8 Mod 3 = {8 Mod 3}") Console.WriteLine($"-8 Mod 3 = {-8 Mod 3}") Console.WriteLine($" 8 Mod -3 = {8 Mod -3}") Console.WriteLine($"-8 Mod -3 = {-8 Mod -3}") End Sub End Module ' The example displays the following output: ' 8 Mod 3 = 2 ' -8 Mod 3 = -2 ' 8 Mod -3 = 2 ' -8 Mod -3 = -2
Remarks
If either number1
or number2
is a floating-point value, the floating-point remainder of the division is returned. The data type of the result is the smallest data type that can hold all possible values that result from division with the data types of number1
and number2
.
If number1
or number2
evaluates to Nothing, it is treated as zero.
Related operators include the following:
-
The Operator (Visual Basic) returns the integer quotient of a division. For example, the expression
14 4
evaluates to 3. -
The / Operator (Visual Basic) returns the full quotient, including the remainder, as a floating-point number. For example, the expression
14 / 4
evaluates to 3.5.
Attempted division by zero
If number2
evaluates to zero, the behavior of the Mod
operator depends on the data type of the operands:
- An integral division throws a xref:System.DivideByZeroException exception if
number2
cannot be determined in compile-time and generates a compile-time errorBC30542 Division by zero occurred while evaluating this expression
ifnumber2
is evaluated to zero at compile-time. - A floating-point division returns xref:System.Double.NaN?displayProperty=nameWithType.
Equivalent formula
The expression a Mod b
is equivalent to either of the following formulas:
a - (b * (a b))
a - (b * Fix(a / b))
Floating-point imprecision
When you work with floating-point numbers, remember that they do not always have a precise decimal representation in memory. This can lead to unexpected results from certain operations, such as value comparison and the Mod
operator. For more information, see Troubleshooting Data Types.
Overloading
The Mod
operator can be overloaded, which means that a class or structure can redefine its behavior. If your code applies Mod
to an instance of a class or structure that includes such an overload, be sure you understand its redefined behavior. For more information, see Operator Procedures.
Example 1
The following example uses the Mod
operator to divide two numbers and return only the remainder. If either number is a floating-point number, the result is a floating-point number that represents the remainder.
[!code-vbVbVbalrOperators#31]
Example 2
The following example demonstrates the potential imprecision of floating-point operands. In the first statement, the operands are Double
, and 0.2 is an infinitely repeating binary fraction with a stored value of 0.20000000000000001. In the second statement, the literal type character D
forces both operands to Decimal
, and 0.2 has a precise representation.
[!code-vbVbVbalrOperators#32]
See also
- xref:Microsoft.VisualBasic.Conversion.Int%2A
- xref:Microsoft.VisualBasic.Conversion.Fix%2A
- Arithmetic Operators
- Operator Precedence in Visual Basic
- Operators Listed by Functionality
- Troubleshooting Data Types
- Arithmetic Operators in Visual Basic
- Operator (Visual Basic)
You can use the Mod operator in VBA to calculate the remainder of a division.
Here are two common ways to use this operator in practice.
Method 1: Use Mod Operator with Hard Coded Values
Sub UseMod()
Range("A1") = 20 Mod 6
End Sub
This particular example will return the remainder of 20 divided by 6 in cell A1.
Method 2: Use Mod Operator with Cell References
Sub UseMod()
Range("C2") = Range("A2") Mod Range("B2")
End Sub
This particular example will calculate the remainder of the value in cell A2 divided by the value in cell B2 and output the result in cell C2.
The following examples show how to use each method in practice.
Example 1: Use Mod Operator with Hard Coded Values
Suppose we would like to calculate the remainder of 20 divided by 6 and output the result in cell A1.
We can create the following macro to do so:
Sub UseMod()
Range("A1") = 20 Mod 6
End Sub
When we run this macro, we receive the following output:
The result of 20 Mod 6 turns is 2.
This value is shown in cell A1, just as we specified in the macro.
Note: The value “6” goes into “20” three times and has a remainder of 2. This is how 20 Mod 6 is calculated.
Example 2: Use Mod Operator with Cell References
Suppose we would like to calculate the remainder of the value in cell A2 divided by the value in cell B2 and output the result in cell C2.
We can create the following macro to do so:
Sub UseMod()
Range("C2") = Range("A2") Mod Range("B2")
End Sub
When we run this macro, we receive the following output:
The result of 20 Mod 6 turns is 2.
This value is shown in cell C2, just as we specified in the macro.
Note: You can find the complete documentation for the VBA Mod operator here.
Additional Resources
The following tutorials explain how to perform other common tasks in VBA:
VBA: How to Sum Values in Range
VBA: How to Calculate Average Value of Range
VBA: How to Count Number of Rows in Range
Excel VBA MOD Operator
In VBA, MOD is the same as the application in mathematics. For example, when we divide a number by its divisor, we get a reminder from that division. This function one may use to give us that remainder from the division. It is not a function in VBA. Rather, it is an operator.
MOD is nothing but MODULO, a mathematical operation. It is the same as the division, but the result is slightly different where division takes the divided amount. But, MOD takes the remainder of the division. For example: If you divide 21 by 2 divisions, the result is 10.50 by MOD is the remainder of the division, i.e., 1. (Number 2 can divide only 20, not 21, so the remainder is 1).
In normal Excel, it is a function. But in VBA, it is not a function. Instead, it is just a mathematical operator. In this article, we will look into this operator in detail.
Table of contents
- Excel VBA MOD Operator
- Syntax
- How to use MOD in VBA?
- Example #1
- Example #2
- Excel MOD Function vs. VBA MOD Operator
- Things to Remember
- Recommended Articles
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA MOD (wallstreetmojo.com)
Syntax
To remind you, this is not a function to have syntax. But, for our reader’s understanding, let me put it in the word.
Number 1 MOD Number 2 (Divisor)
Number 1 is nothing, but what is the number we are trying to divide?
Number 2 is the divisor, i.e., we will divide Number 1 by this divisor.
MOD is the result given by Number 1 / Number 2.
How to use MOD in VBA?
You can download this VBA MOD Function Template here – VBA MOD Function Template
Example #1
Follow the below steps to write the code.
Step 1: Create a macro name.
Code:
Sub MOD_Example1() End Sub
Step 2: Define one of the variables as “Integer.”
Code:
Sub MOD_Example1() Dim i As Integer End Sub
Step 3: Now perform the calculation as “i = 20 MOD 2.”
As we said in the beginning, MOD is an operator, not a function. So, we have used the word MOD like how we enter a plus (+).
Code:
Sub MOD_Example1() Dim i As Integer i = 21 Mod 2 End Sub
Step 4: Now, assign the value of “I” to the message box.
Code:
Sub MOD_Example1() Dim i As Integer i = 21 Mod 2 MsgBox i End Sub
Step 5: Run the code message box that will show the value of “I.”
Example #2
The MOD function in VBA always returns an integer value, i.e., without decimals if you supply the number in decimals. For example, look at the below code.
Code:
Sub MOD_Example2() Dim i As Integer i = 26.25 Mod 3 MsgBox i End Sub
Divisor 3 can divide 24, so the remainder here is 2.25. But the MOD operator returns the integer value, i.e., 2, not 2.25.
Now, we will modify the number to 26.51 and see the difference.
Code:
Sub MOD_Example2() Dim i As Integer i = 26.51 Mod 3 MsgBox i End Sub
We will run this code and see what the result is.
We have got zero as the answer. We got zero because VBA roundsRound function in VBA is a mathematical function that rounds up or down the given number to the specific set of decimal places specified by the user to ease calculation.read more the numbers like our bankers do, i.e., it will round up any decimal point greater than 0.5 to the next integer value. So, in this case, 26.51 is rounded up to 27.
Since 3 can divide the 27 by 9, we will not get any remainder values, so the value of i equals zero.
Now, we will supply the divisor value also in decimal points.
Code:
Sub MOD_Example2() Dim i As Integer i = 26.51 Mod 3.51 MsgBox i End Sub
Step 6: Run this code and see what the result is.
We got 3 as the answer because 26.51 rounded up to 27, and the divisor value 3.51 will be rounded up to 4.
So, if you divide 27 by 4, the remainder is 3.
Excel MOD Function vs. VBA MOD Operator
Step 1: Now, look at the difference between excel and VBA MOD operator. We have a value of 54.24. The divisor value is 10.
Step 2: If we apply the MOD function, we will get the result of 4.25.
Step 3: But if you do the same operation with VBA, we will get 4 as the remainder, not 4.25.
Code:
Sub MOD_Example2() Dim i As Integer i = 54.25 Mod 10 MsgBox i End Sub
Step 4: Run this code and see what the result is.
Things to Remember
- It is not a function, but it is an arithmetic operator.
- It is roundup and rounddown decimal values, unlike our MOD function in the worksheet function.
Recommended Articles
This article has been a guide to VBA MOD Function. Here, we learned how to use the modulo, practical examples, and a downloadable Excel template. Below you can find some useful Excel VBA articles: –
- VBA Return Statement
- VBA RoundUp
- VBA Cell References
- What is VBA Range?
- VBA Randomize
VBA MOD
VBA Mod is not a function, in fact, it is an operation which is used for calculating the remainder digit by dividing a number with divisor. In simple words, it gives us the remainder value, which is the remained left part of Number which could not get divided completely.
How to Use VBA MOD Function?
We will discuss how to use VBA MOD Function by using some examples.
You can download this VBA MOD Function Excel Template here – VBA MOD Function Excel Template
Example #1
Press Alt + F11 to go in VBA coding mode. After that go to insert menu and select Module to open a new module.
Now open the body of syntax as shown below. We have names the macro subcategory as VBA_MOD. By this, it will become easy for users to identify the code to run.
Code:
Sub VBA_MOD() End Sub
Now as we are calculating the Mod which includes numbers for that, define an Integer “A”. This can be any alphabet as shown in below screenshot.
Code:
Sub VBA_MOD() Dim A As Integer End Sub
Now we will implement and test the same example which we have seen above. For this, in defined integer, we will write 12 Mod 5. This is a way to write the Mod operation in VBA and with the answer in the message box with msg function as shown below.
Code:
Sub VBA_MOD() Dim A As Integer A = 12 Mod 5 MsgBox A End Sub
Once done, run the complete code by using F5 key or clicking on the play button as shown below. We will see the output of 12 Mod 5 as 2 which is the remainder obtained after dividing 12 by 5.
Example #2
There is another way to calculate the MOD in VBA. For this, we will see a decimal number and find how MOD.
Press Alt + F11 to go in VBA coding mode. After that go to insert menu and select Module to open a new module.
In opened new Module frame the syntax. Here we have named the macro subcategory as VBA_MOD1. By this, we will be able to differentiate the name of Marco sequence. Which we will see ahead.
Code:
Sub VBA_MOD1() End Sub
Now select an active cell where we need to see the result by ActiveCell.FormulaR1C1 as cell C1. Now Mod reference cell -2 and -1 are considered as cell A1 and cell B1 respectively as shown below.
Code:
Sub VBA_MOD1() ActiveCell.FormulaR1C1 = "=MOD(RC[-2],RC[-1])" End Sub
Now select the reference cell as Range where we will the output with Range(“C3”).Select. This will allow cell C3 to take the range of respective cells from -2 and -1 limit.
Code:
Sub VBA_MOD1() ActiveCell.FormulaR1C1 = "=MOD(RC[-2],RC[-1])" Range("C3").Select End Sub
Now, Run the code using F5 key or click on the play button which is located below the menu bar of VBA Application window as shown below.
As we can see in the above screenshot, the output of VBA Coding is coming as 1.4.
We can assign the written code to a button where can directly click and run the code instead of running the code in by select the macro. For this go to the Developer tab and click on Design Mode as shown below.
This will allow us to design different tabs without affecting the written code. Now go to Insert option under Developer tab which is just beside the Design Mode option. Then select a Button as shown below.
Now draw the selected button and name it as MOD with the name of operation which we will be going to perform.
Right click on created MOD Button and select Assign Marco from the right click list.
Now from the Assign Marco window, select the created macro. Once done, click on Ok as shown below.
Now to test the assigned macro in the created button, exit from Design Mode. Then put the cursor where we need to see the output as shown below.
Now click on MOD Button to see the result as shown below.
As we can see in the above screenshot, we have got the output as 1.4 which is Mod of number 23.4 with by divisor 2.
Pros of VBA MOD
- We can calculate Mod of multiple criteria with the help of VBA Mod in quick time.
- An obtained result from the Excel function and VBA Code will be the same.
Things to Remember
- Don’t forget the save the file in Macro Enable Worksheet. This will allow us to use that file multiple time without losing the written code.
- Always compile the code before running. This will detect the error instead of getting error while actual run.
- It is recommended to assign the written code to a Button. This process saves time.
Recommended Articles
This has been a guide to Excel VBA MOD. Here we discussed how to use VBA MOD Function to remove spaces along with some practical examples and downloadable excel template. You can also go through our other suggested articles-
- VBA TRIM
- VBA Arrays
- VBA Select Case
- VBA Find