Округление переменной excel vba

Округление чисел в VBA Excel с помощью оператора Round и встроенной функции рабочего листа WorksheetFunction.Round. Особенности бухгалтерского и обычного округления.

Оператор Round

А вы знаете, что при использовании для округления чисел в VBA Excel оператора Round, вы можете получить совершенно не тот результат, который ожидали? И ведь это действительно так!

Скопируйте в модуль VBA следующую процедуру и запустите ее выполнение:

Sub Test_1()

Dim a1 As Single, a2 As Single, a3 As Single, a4 As Single

a1 = Round(1.5, 0)

a2 = Round(2.5, 0)

a3 = Round(3.5, 0)

a4 = Round(4.5, 0)

MsgBox «Round(1.5, 0)=» & a1 & vbNewLine & _

       «Round(2.5, 0)=» & a2 & vbNewLine & _

       «Round(3.5, 0)=» & a3 & vbNewLine & _

       «Round(4.5, 0)=» & a4

End Sub

В результате вы получите это:

Информационное сообщение с результатами бухгалтерского округления
Удивительно, не правда ли? Как же так получилось?
Дело в том, что оператор Round осуществляет «бухгалтерское» (или «банковское») округление, которое призвано при большом количестве таких операций свести погрешность к минимуму. Это достигается за счет того, что оператор Round использует при округлении правило, отличное от того, которое мы знаем еще со школы, когда округляемое число увеличивается на единицу, если отбрасываемое число равно пяти. Суть округления с помощью оператора Round состоит в том, что если перед отбрасываемой пятеркой стоит нечетная цифра, то она увеличивается на единицу (округление вверх), а если перед ней стоит четная цифра, то она не увеличивается (округление вниз).

Еще можно сформулировать «бухгалтерское» округление так: при отбрасывании пятерки число округляется к ближайшему четному. Обратите внимание, что в результатах нашего примера все полученные числа — четные.
Проверим погрешность:

  1. Сумма исходных чисел: 1.5 + 2.5 + 3.5 +4.5 = 12
  2. Сумма округленных чисел: 2 + 2 + 4 + 4 = 12

Результат получился просто идеальный для приведенного примера, так как суммы исходных и округленных чисел равны.

Оператор WorksheetFunction.Round

Если вам необходимо общепринятое математическое округление, используйте встроенную функцию рабочего листа —  WorksheetFunction.Round.

Скопируйте в модуль VBA процедуру с использованием WorksheetFunction.Round и запустите ее выполнение:

Sub Test_2()

Dim a1 As Single, a2 As Single, a3 As Single, a4 As Single

a1 = WorksheetFunction.Round(1.5, 0)

a2 = WorksheetFunction.Round(2.5, 0)

a3 = WorksheetFunction.Round(3.5, 0)

a4 = WorksheetFunction.Round(4.5, 0)

MsgBox «WorksheetFunction.Round(1.5, 0)=» & a1 & vbNewLine & _

       «WorksheetFunction.Round(2.5, 0)=» & a2 & vbNewLine & _

       «WorksheetFunction.Round(3.5, 0)=» & a3 & vbNewLine & _

       «WorksheetFunction.Round(4.5, 0)=» & a4

End Sub

Результат будет следующий:

Информационное сообщение с результатами общепринятого округления

Получилось то, что мы и ожидали.

Проверим погрешность:

  1. Сумма исходных чисел: 1.5 + 2.5 + 3.5 +4.5 = 12
  2. Сумма округленных чисел: 2 + 3 + 4 + 5 = 14

Результат очевиден — в данном случае сумма округленных чисел на 2 единицы больше суммы исходных.

Исходя из этого результата, можно сделать вывод, что «банковское» округление с помощью оператора Round дает более точные результаты при массовых операциях с округленными числами. Но в повседневной жизни чаще встречается обычное математическое округление.

Выбирайте округление, которое вам больше подходит для решаемой задачи!

In this Article

  • VBA Round
  • Syntax of the VBA Round Function
  • VBA Round a Variable
    • VBA Rounding Results
  • VBA Round Cell Value
  • VBA RoundUp Function
    • RoundUp to the Nearest Whole Number
    • RoundUp Function Results
  • VBA RoundDown Function
    • RoundDown to the Nearest Whole Number
    • RoundDown Function Results
  • Other VBA Rounding Functions
    • VBA Ceiling – RoundUp to A Specified Significance
    • VBA RoundUp To Specified Significance Results
    • VBA Floor – RoundDown to A Specified Significance
    • VBA RoundDown to Specified Significance Results

VBA Round

The VBA Round Function rounds numbers to a specified number of digits.

Syntax of the VBA Round Function

The syntax of the VBA Round Function is:

Round(Expression, [Decimal_places]) where:

  • Expression – The number to round.
  • Decimal_places (Optional) – An integer that specifies the number of decimal places to round. The value must be greater than or equal to 0 (>=0). If blank, the default of 0 is used, which means the function rounds to the nearest integer.

So, let’s look at an example so that you can see how the VBA Round function works, rounding to 1 decimal place:

Sub Round1()

Msgbox Round(7.25, 1)

End Sub

The resulting MessageBox:

VBA Round to 1 Decimal

VBA Round a Variable

In the above example, we entered the to-be-rounded number directly into the function, usually however, you’d round a variable instead. The following is an example using a variable instead:

Note: We use the Double variable type in order to store decimal values.

Sub RoundUsingVariable()

Dim unitcount As Double

unitcount = 7.25

MsgBox "The value is " & Round(unitcount, 1)

End Sub

The result is:

Rounding to 1 decimal place with a variable example

VBA Rounding Results

Actual Number Number of Decimal Places Result
7.25 0 7
7.25 1 7.2
7.25 2 7.25
-7.25 1 -7.2
-7.25 2 -7.25

VBA Round Cell Value

You can also round a cell value directly in VBA:

Sub RoundCell()
Range("A1").Value = Round(Range("A1").Value, 2)
End Sub

VBA RoundUp Function

Let’s say you want to round a number up, using VBA. There is no built-in VBA RoundUp equivalent function, instead what you can do is call the Excel RoundUp Worksheet function from your VBA code:

roundupUnitcount = Application.WorksheetFunction.RoundUp(unitcount, 3)

Excel’s worksheet functions are available to use in VBA, through the use of the WorksheetFunction object. The only worksheet functions that you can’t call, are those that already have a built-in VBA equivalent.

A reminder of the syntax of the Excel Worksheet RoundUp Function:

ROUNDUP(Number, Digits) where:

  • Number – The number that you would like rounded up.
  • Digits – The number of digits that you would like to round the number.

So, let’s look at an example, so that you can see how to access the RoundUp Worksheet function in your VBA code:

Sub RoundUp()

Dim unitcount As Double

Dim roundupUnitcount As Double

unitcount = 7.075711

roundupUnitcount = Application.WorksheetFunction.RoundUp(unitcount, 4)

MsgBox "The value is " & roundupUnitcount

End Sub

The result is:

Rounding Up to Four Decimal Places using VBA

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

RoundUp to the Nearest Whole Number

You can round up to the nearest whole number by specifying 0 as the number of decimal places:

Sub RoundUpWhole()

MsgBox Application.WorksheetFunction.RoundUp(7.1, 0)

End Sub

The result delivered:

Rounding Up to the Nearest Integer using VBA

RoundUp Function Results

Actual Number Digits Result
7.075711 0 8
7.075711 1 7.1
7.075711 2 7.08
7.075711 3 7.076
7.075711 -1 10
7.075711 -2 100
7.075711 -3 1000

VBA RoundDown Function

Let’s say you want to round a number down, using VBA. There is no built-in VBA RoundDown equivalent function either, instead again, what you would do is call the Excel RoundDown Worksheet function from your VBA code.

A reminder of the syntax of the Excel Worksheet RoundDown Function:

ROUNDDOWN(Number, Digits) where:

• Number – The number that you would like rounded down.
• Digits – The number of digits that you would like to round the number.

So, let’s look at an example, so that you can see how to access the RoundDown Worksheet function in your VBA code:

Sub RoundDown()

Dim unitcount As Double

Dim rounddownUnitcount As Double

unitcount = 5.225193

rounddownUnitcount = Application.WorksheetFunction.RoundDown(unitcount, 4)

MsgBox "The value is " & rounddownUnitcount

End Sub

The result is:

VBA RoundDown

VBA Programming | Code Generator does work for you!

RoundDown to the Nearest Whole Number

You can round down to the nearest whole number by specifying 0 as the number of decimal places:

Sub RoundDownWhole()

MsgBox Application.WorksheetFunction.RoundDown(7.8, 0)

End Sub

The result is:

VBA RoundDown to Nearest Integer

RoundDown Function Results

Actual Number Digits Result
5.225193 0 5
5.225193 1 5.2
5.225193 2 5.22
5.225193 3 5.225
5.225193 -1 0
5.225193 -2 0
5.225193 -3 0

Other VBA Rounding Functions

VBA Ceiling – RoundUp to A Specified Significance

VBA does not have a Ceiling.Math function equivalent, so if you want to round a number up to the nearest integer or to the nearest specified multiple of significance, then you can call Excel’s Ceiling.Math worksheet function from your VBA code.

A reminder of the syntax of the Excel Worksheet Ceiling.Math Function:

CEILING.MATH(Number, [Significance], [Mode]) where:

  • Number – The number that you would like to round up.
  • Significance (Optional) – The multiple to which you want your number to be rounded to.
  • Mode (Optional) – Controls whether negative numbers are rounded towards or away from zero.

So, let’s look at an example, so that you can see how to access the Ceiling.Math Worksheet function in your VBA code:

Sub RoundUpToSignificance()

Dim unitcount As Double

Dim ceilingmathUnitcount As Double

unitcount = 4.1221 

ceilingmathUnitcount = Application.WorksheetFunction.Ceiling_Math(unitcount, 5)

MsgBox "The value is " & ceilingmathUnitcount

End Sub

The result is:

VBA RoundUp With Ceiling.Math

VBA RoundUp To Specified Significance Results

Actual Number Significance Mode Result
4.1221 5
4.1221 3 6
4.1221 50 50
-4.1221 3 -3
-4.1221 3 -1 -6

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA Floor – RoundDown to A Specified Significance

VBA does not have a Floor.Math function equivalent either. However, once again, if you want to round a number down to the nearest integer or to the nearest specified multiple of significance, then you can call Excel’s Floor.Math worksheet function from VBA.

A reminder of the syntax of the Excel Worksheet Floor.Math Function:

FLOOR.MATH(Number, [Significance], [Mode]) where:
• Number – The number that you would like to round down.
• Significance (Optional) – The multiple to which you want your number to be rounded to.
• Mode (Optional) – Controls whether negative numbers are rounded towards or away from zero.

So, let’s look at an example, so that you can see how to access the Floor.Math Worksheet function in your VBA code:

Sub RoundDownToSignificance()

Dim unitcount As Double
Dim floormathUnitcount As Double

unitcount = 4.55555559
floormathUnitcount = Application.WorksheetFunction.Floor_Math(unitcount, 2)

MsgBox "The value is " & floormathUnitcount

End Sub

The result is:

VBA RoundDown to Specified Significance

VBA RoundDown to Specified Significance Results

Actual Number Significance Mode Result
4.55555559 4
4.55555559 3 3
4.55555559 50 0
-4.55555559 3 -6
-4.55555559 3 -1 -3

Очень часто при создании алгоритмов подсчета тех или иных значений полученные результаты имеют значение десятичной дроби с большим количеством знаков после запятой. Работать с такими данными и отображать их не очень удобно и некрасиво. 
Рассмотрим какими функциями следует округлять данные в коде vba Excel.

Первый способ округления при помощью функции int().

Данная функция выводит целое значение до запятой. При округлении отрицательных чисел int округляет десятичную дробь до большего целого значения.
Например: число Пи с минусом после округления — int (-3.1415926535 ) будет равно 4 (четырем целым).

Второй способ округление при помощи функции fix()

происходит аналогично с int . Отличается эта функция тем, что округляет отрицательные числа до меньшего значения. Так округлённое число  Пи со знаком минус  будет  fix( -3.1415926535) = 3.
Если требуется не просто убрать дробную часть, а округлить до целого числа, можно использовать следующую функцию cint().
Пример:
Cint(fix( -3.1415926535)) = 3
Cint(int( -3.1415926535)) = 3

Число пи картинка

Как округлять до десятых и сотых (один и два знака после запятой, соответственно).

Для округления до десятых следует умножить переменную на 10 (десять), после чего округлить до целых и разделить на 10 (десять).
Пример:
Cint(int( -3.1415926535*10))/10 = 3.1
Cint(fix( -3.1415926535*10))/10 = 3.1

Для округления до сотых следует проделать ту же самую операцию, только умножать и делить не на 10, а на 100.
Пример:
Cint(int( -3.1415926535*100))/100 = 3.14
Cint(fix( -3.1415926535*100))/100 = 3.14

Пример кода округляющего значения из textbox, запускающийся нажатием кнопки CommandButtom1:

Private sub CommandButtom1_click()
textbox2.value = Cint(int(textbox1.value *100))/100
END SUB

Видео с примером работы макроса:

Как видите, ничего сложного в округлении чисел в vba Excel нет. Удачи Вам в изучении программы


You can use the RoundUp method in VBA to round values up.

This function uses the following basic syntax:

Sub RoundUpValue()
    Range("B1") = WorksheetFunction.RoundUp(Range("A1"), 0)
End Sub

This particular example will round up the value in cell A1 to the nearest whole number and display the result in cell B1.

Note that the second argument in the RoundUp method specifies the number of digits to round where:

  • -3 rounds up to the nearest thousand
  • -2 rounds up to the nearest hundred
  • -1 rounds up to the nearest ten
  • 0 rounds up to the nearest whole number
  • 1 rounds up to the nearest tenth (one decimal place)
  • 2 rounds up to the nearest hundredth (two decimal places)
  • 3 rounds up to the nearest thousandth (three decimal places)

And so on.

The following examples show how to use the RoundUp method in practice.

Example 1: Round Up to Nearest Whole Number in VBA

We can create the following macro to round up the value in cell A1 to the nearest whole number and display the result in cell B1:

Sub RoundUpValue()
    Range("B1") = WorksheetFunction.RoundUp(Range("A1"), 0)
End Sub

When we run this macro, we receive the following output:

Notice that the value 1,432.78 in cell A1 has been rounded up to the nearest whole number of 1,433 in cell B1.

Example 2: Round Up to Nearest Hundred in VBA

We can create the following macro to round up the value in cell A1 to the nearest hundred and display the result in cell B1:

Sub RoundUpValue()
    Range("B1") = WorksheetFunction.RoundUp(Range("A1"), -2)
End Sub

When we run this macro, we receive the following output:

Notice that the value 1,432.78 in cell A1 has been rounded up to the nearest hundred of 1,500 in cell B1.

Example 3: Round Up to Nearest Tenth in VBA

We can create the following macro to round up the value in cell A1 to the nearest tenth (i.e. one decimal place) and display the result in cell B1:

Sub RoundUpValue()
    Range("B1") = WorksheetFunction.RoundUp(Range("A1"), 1)
End Sub

When we run this macro, we receive the following output:

Notice that the value 1,432.78 in cell A1 has been rounded up to the nearest tenth of 1,432.8 in cell B1.

Note: You can find the complete documentation for the VBA RoundUp method here.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

VBA: How to Write SUMIF and SUMIFS Functions
VBA: How to Write COUNTIF and COUNTIFS Functions
VBA: How to Write AVERAGEIF and AVERAGEIFS Functions

В этом учебном материале вы узнаете, как использовать Excel функцию ROUND (в VBA) с синтаксисом и примерами.

Описание

Microsoft Excel функция ROUND возвращает число, округленное до указанного количества знаков.
Функция ROUND — это встроенная в Excel функция, которая относится к категории математических / тригонометрических функций. Её можно использовать как функцию VBA в Excel.
В качестве функции VBA вы можете использовать эту функцию в коде макроса, который вводится через редактор Microsoft Visual Basic.

Пожалуйста, прочтите нашу страницу функции ОКРУГЛ (WS), если вы ищете версию функции ОКРУГЛ для рабочего листа, так как она имеет совершенно другой синтаксис.

Очень важно отметить, что функция VBA ROUND ведет себя немного странно и использует то, что обычно называют банковским округлением. Поэтому перед использованием этой функции прочтите следующее: Функция ROUND использует логику округления до четного. Если округляемое выражение оканчивается на 5, функция ROUND округляет выражение так, чтобы последняя цифра была четным числом.
Например:

Round(12.55, 1)

Результат: 12.6  (округляет вверх)

Round(12.65, 1)

Результат: 12.6  (округляет вниз)

Round(12.75, 1)

Результат: 12.8  (округляет вверх)

В этих случаях последняя цифра после округления всегда является четным числом. Поэтому обязательно используйте функцию ROUND, если это ваш желаемый результат.

Синтаксис

Синтаксис функции ROUND в Microsoft Excel:

Round ( expression, [decimal_places] )

Аргументы или параметры

expression
Числовое выражение, которое нужно округлить.
decimal_places
Необязательно. Это количество десятичных знаков, до которого нужно округлить expression. Если этот параметр не указан, функция ROUND вернет целое число.

Возвращаемое значение

Функция ROUND возвращает числовое значение.

Применение

  • Excel для Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 для Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Тип функции

  • Функция VBA

Пример (как функция VBA)

В среде VBA Excel функция ROUND возвращает число, округленное до указанного количества десятичных знаков. Напоминаем, что функция ROUND использует то, что обычно называют банковским округлением. Поэтому будьте осторожны перед использованием этой функции.
Функция ROUND может использоваться в коде VBA в Microsoft Excel.
Вот несколько примеров того, что вернет функция ROUND:

Round(210.665, 2)

Результат: 210.66 ‘пример банковского округления

Round(210.67, 1)

Результат: 210.7

Round(210.67, 0)

Результат: 211

Round(210.67)

Результат: 211

Например:

Dim LNumber As Double

LNumber = Round(210.67, 1)

В этом примере переменная с именем LNumber теперь будет содержать значение 210,7.

Понравилась статья? Поделить с друзьями:
  • Округление отрицательных чисел в excel
  • Округление ответа в excel
  • Округление к диапазону excel
  • Округление к ближайшему целому в excel
  • Округление до четных excel