Округлить значение vba excel

Округление чисел в 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

totn Excel Functions


This Excel tutorial explains how to use the Excel ROUND function (in VBA) with syntax and examples.

Description

The Microsoft Excel ROUND function returns a number rounded to a specified number of digits.

The ROUND function is a built-in function in Excel that is categorized as a Math/Trig Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.

Please read our ROUND function (WS) page if you are looking for the worksheet version of the ROUND function as it has a very different syntax.

It is very important to note that the VBA ROUND function behaves a little peculiar and uses something commonly referred to as bankers rounding. So before using this function, please read the following:

The ROUND function utilizes round-to-even logic. If the expression that you are rounding ends with a 5, the ROUND function will round the expression so that the last digit is an even number.

For example:

Round(12.55, 1)
Result: 12.6   (rounds up)

Round(12.65, 1)
Result: 12.6   (rounds down)

Round(12.75, 1)
Result: 12.8   (rounds up)

In these cases, the last digit after rounding is always an even number. So, be sure to only use the ROUND function if this is your desired result.

Syntax

The syntax for the ROUND function in Microsoft Excel is:

Round ( expression, [decimal_places] )

Parameters or Arguments

expression
A numeric expression that is to be rounded.
decimal_places
Optional. It is the number of decimal places to round the expression to. If this parameter is omitted, then the ROUND function will return an integer.

Returns

The ROUND function returns a numeric value.

Applies To

  • Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Type of Function

  • VBA function (VBA)

Example (as VBA Function)

In Excel’s VBA environment, the ROUND function returns a number rounded to a specified number of decimal places. As a reminder, the ROUND function uses something commonly referred to as bankers rounding. So please be careful before using this function.

The ROUND function can be used in VBA code in Microsoft Excel. Here are some examples of what the ROUND function would return:

Round(210.665, 2)
Result: 210.66  'example of bankers rounding

Round(210.67, 1)
Result: 210.7

Round(210.67, 0)
Result: 211

Round(210.67)
Result: 211

For example:

Dim LNumber As Double

LNumber = Round(210.67, 1)

In this example, the variable called LNumber would now contain the value of 210.7.

Tip to Avoid Bankers Rounding:

If you want to avoid bankers rounding, you can create your own custom function as follows:

' This function overcomes the bankers Rounding that occurs in the
' built-in VBA Round function to provide true (symmetric) numeric Rounding
' Created by TechOnTheNet.com
Public Function StandardRound(pValue As Double, pDecimalPlaces As Integer) As Variant

    Dim LValue As String
    Dim LPos As Integer
    Dim LNumDecimals As Long
    Dim LDecimalSymbol As String
    Dim QValue As Double

    ' Return an error if the decimal places provided is negative
    If pDecimalPlaces < 0 Then
       StandardRound = CVErr(2001)
          Exit Function
    End If

    ' If your country uses a different symbol than the "." to denote a decimal
    ' then change the following LDecimalSymbol variable to that character
    LDecimalSymbol = "."

    ' Determine the number of decimal places in the value provided using
    ' the length of the value and the position of the decimal symbol
    LValue = CStr(pValue)
    LPos = InStr(LValue, LDecimalSymbol)
    LNumDecimals = Len(LValue) - LPos

    ' Round if the value provided has decimals and the number of decimals
    ' is greater than the number of decimal places we are rounding to
    If (LPos > 0) And (LNumDecimals > 0) And (LNumDecimals > pDecimalPlaces) Then

        ' Calculate the factor to add
        QValue = (1 / (10 ^ (LNumDecimals + 1)))

        ' Symmetric rounding is commonly desired so if the value is
        ' negative, make the factor negative
        ' (Remove the following 3 lines if you require "Round Up" rounding)
        If (pValue < 0) Then
            QValue = -QValue
        End If

        ' Add a 1 to the end of the value (For example, if pValue is 12.65
        ' then we will use 12.651 when rounding)
        StandardRound = Round(pValue + QValue, pDecimalPlaces)

    ' Otherwise return the original value
    Else
        StandardRound = pValue
    End If

End Function

And then call the StandardRound function instead of using the Round function.

Frequently Asked Questions

Question: I read your explanation of how the ROUND function works in VBA using the round-to-even logic. However, I really need to round some values in the traditional sense (where 5 always rounds up). How can I do this?

Answer: You could always use the following logic:

If you wanted to round 12.65 to 1 decimal place in the traditional sense (where 12.65 rounded to 1 decimal place is 12.7, instead of 12.6), try adding 0.000001 to your number before applying the ROUND function:

Round(12.45+0.000001,1)

By adding the 0.000001, the expression that you are rounding will end in 1, instead of 5…causing the ROUND function to round in the traditional way.

And the 0.000001 does not significantly affect the value of your expression so you shouldn’t introduce any calculation errors.

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