Excel vba остаток при делении

Арифметические (математические) операторы, использующиеся в 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. «^» – возведение в степень;
  2. «» – отрицание;
  3. «*» и «/» – умножение и деление;1
  4. «» – целочисленное деление;
  5. «Mod» – остаток от деления двух чисел;
  6. «+» и «» – сложение и вычитание.2

1 Если умножение и деление выполняются в одном выражении, то каждая такая операция выполняется слева направо в порядке их следования.
2 Если сложение и вычитание выполняются в одном выражении, то каждая такая операция выполняется слева направо в порядке их следования.

Для переопределения приоритета выполнения математических операторов в VBA Excel используются круглые скобки. Сначала выполняются арифметические операторы внутри скобок, затем — операторы вне скобок. Внутри скобок приоритет операторов сохраняется.

a = 3 ^ 2 + 1 ‘a = 10

a = 3 ^ (2 + 1) ‘a = 27

a = 3 ^ (2 + 1 * 2) ‘a = 1

Home / VBA / How to use MOD in VBA

In VBA, MOD is an operator, not a function and this operator helps you to divide two numbers and returns the remainder value in the result.

It’s equivalent to the mod function in Excel.

You can use the mod in so many ways and, in this tutorial, we will see some examples. Use the below steps to use the mod operator in VBA:

Range("A1") = 10 Mod 3
  1. Specify the first number which you want to get divided.
  2. After that, enter the “mod” operator.
  3. Now, enter a number that you want to divide by.
  4. In the end, use a message box or a cell to get the remainder from the division.
mod-in-vba

In the same way, you can also get the remainder using a message box.

And in the following code, we have used a message box and then used the mod operator to get the remainder after dividing.

MsgBox 9 Mod 3

And when you run this code, it returns zero in the result in the message box as when you divide 9 by 3 there’s no remainder left, so as in the result of this code.

message-box

Note: As I said, there’s also a function in Excel to get the remainder from the division of two numbers and there are a few situations where you will find that the result you get from Excel will be different from the result you got in VBA.

Error in MOD

If you try to divide a number with zero it always returns a division by zero error.

Debug.Print 10 Mod 0

And the above code returns that error.

VBA MOD

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.

Insert 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

VBA MOD Example 1-1

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

VBA MOD Example 1-2

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

VBA MOD Example 1-3

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.

VBA MOD Example 1-4 

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.

Insert 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

VBA MOD Example 2-1

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

VBA MOD Example 2-2

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

VBA MOD Example 2-3

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.

VBA MOD Example 2-4

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.

Design Mode

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.

Insert Button

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.

Assign Macro

Now from the Assign Marco window, select the created macro. Once done, click on Ok as shown below.

Assign Macro to Button

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.

VBA MOD Example 2-5

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-

  1. VBA TRIM
  2. VBA Arrays
  3. VBA Select Case
  4. VBA Find

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

VBA-MOD-Function

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.”

VBA MOD Example 1

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.

VBA MOD Example 2

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.

Example 2-1

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.

VBA MOD Example 2-2

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.

Example 3

Step 2: If we apply the MOD function, we will get the result of 4.25.

Example 3-1

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.

VBA MOD Example 3-2

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 »

28 Апрель 2011              129100 просмотров

  • ABS() — эта функция возвращает абсолютное значение переданного ей числа (то же число, но без знака). Например, ABS(3) и ABS(-3) вернут одно и то же значение 3.
  • Int(), Fix() и Round()позволяют по разному округлять числа:
    • Int() возвращает ближайшее меньшее целое;
    • Fix() отбрасывает дробную часть;
    • Round() округляет до указанного количества знаков после запятой.

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

    то результатом будет 2,5, хотя предполагалось получить 2,51. Поэтому порой для округления лучше использовать Format:

        MsgBox Format(2.505, "#,##0.00")

    но в этом случае мы получим не число в чистом виде, а текст. И если нужно именно число, то придется производить дополнительные преобразования:

        MsgBox CDbl(Format(2.505, "#,##0.00"))

    Так же, для математического округления, можно использовать и такой вариант:

        MsgBox Application.Round(2.505, 2)

    Но здесь стоит учитывать, что это не чистый VB и этот метод сработает только в Excel, т.к. по сути мы обращаемся к встроенной в Excel функции округления ОКРУГЛ(ROUND), которая применяет именно математическое округление.

  • Rnd и команда Randomize используются для получения случайных значений (очень удобно для генерации имен файлов и в других ситуациях). Перед вызовом функции Rnd() необходимо выполнить команду Randomize для инициализации генератора случайных чисел.
        Dim lRundNum As Long, lMinNum As Long, lMaxNum As Long
        lMinNum = 1: lMaxNum = 100
        Randomize
        lRundNum = Int(lMinNum + (Rnd() * lMaxNum))
        MsgBox lRundNum
  • Sgn() — позволяет вернуть информацию о знаке числа. Возвращает 1, если число положительное, -1, если отрицательное и 0, если проверяемое число равно 0.
  • Mod() — Делит два числа и возвращает только остаток. Например, выражение 8 Mod 3 вернет число 2, т.к. без остатка(в виде дроби у результата деления) 8 делится на 3 только до 2-х(8 / 3 = 2,66666666666667).
    При этом функция Mod учитывает и знак числа — если первое число или оба числа отрицательные, то результатом будет отрицательное число. Если же отрицательное только второе число — то результат будет положительным числом.
    При попытке получить остаток при делении чисел с плавающей запятой результат может быть не тем, который ожидается, потому что перед выполнением деления оба числа округляются по математическим законам(5 и выше до большего, 4 и ниже — до меньшего). Например, выражение 8 Mod 3.5 вернет 0, а выражение 8 Mod 3.4 — 2.

Понравилась статья? Поделить с друзьями:
  • Excel vba нумерация ячеек
  • Excel vba нулевой значение
  • Excel vba нормальное распределение
  • Excel vba номер текущей строки
  • Excel vba номер строки диапазона