Vba excel функция 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

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.

Округление чисел в 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 дает более точные результаты при массовых операциях с округленными числами. Но в повседневной жизни чаще встречается обычное математическое округление.

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

VBA Round Function in Excel

Excel VBA Round Function

You must have used Excel Round function to round the floating numbers up-to a specific number of decimal places. VBA Round function behaves totally in a different manner than the one you use in Excel. VBA Round function uses “round to even” logic. If the number you are trying to round has the last digit after decimal >= 0.6, VBA Round function rounds it up (Round UP).

If the number you are trying to round have the last digit after decimal <= 0.4, it rounds it down (Round Down). Suppose the decimal part is exactly 0.5 then what does it do? In such cases, it checks with the integer part of the number. If the integer part is even then it rounds down to the even number of the decimal part. If integer part is odd, then it rounds it up to the even number. This method of rounding is also called as “Banker’s rounding”.

Syntax of Round Function in Excel VBA

VBA Round function has the following syntax:

Syntax of Round Function

Where,

  • Expression – The floating number you wanted to round.
  • Decimal_places – It’s an optional argument which takes an integer value which specifies the decimal places up-to which the number is supposed to be round. Should always be greater than or equals to zero. If not specified, by default zero is considered. Which means a number is rounded to an integer.

How to Use Excel VBA Round Function?

We will learn how to use a VBA Round function with few examples in Excel.

You can download this VBA Round Excel Template here – VBA Round Excel Template

Example #1 – VBA Round Function to Round a Number

Follow the below steps to use Round function in Excel VBA.

Step 1: Insert a new module under Visual Basic Editor (VBE).

Module VBA Round Function

Step 2: Define a new sub-procedure to store a macro in VBE.

Code:

Sub Round_Ex1()

End Sub

Sub Round Example 1

Step 3: Use MsgBox function to be able to pop up a message like this “The Value Rounded is:”

Code:

Sub Round_Ex1()

MsgBox "The Value Rounded is: "

End Sub

Sab Round Example 1.2

Step 4: Now, add “& Round (10.9834, 2)” in front of MsgBox command, so that the rounded value will be shown up in the message box along.

Code:

Sub Round_Ex1()

MsgBox "The Value Rounded is: " & Round(10.9834, 2)

End Sub

Sub round Example 1.3

Step 5: Hit F5 or the Run button placed at the uppermost panel to run this code. You will see an output as shown in the below.

Round Example 1 GIF

Example #2 – Round a Variable Using VBA Round

Step 1: Define a new sub-procedure in VBE to store a macro.

Code:

Sub Round_Ex2()

End Sub

Function in excel Example 2.2

Step 2: Define a variable named roundNumber as Double which can hold the value of the number to be rounded.

Code:

Sub Round_Ex2()

  Dim roundNumber As Double

End Sub

Function in excel Example 2.2

Step 3: Assign a number value which is to be rounded to this variable using assignment operator.

Code:

Sub Round_Ex2()

  Dim roundNumber As Double

  roundNumber = 23.98

End Sub

Function in excel Example 2.4

Step 4: Use a combination of MsgBox along with Round function to round this number up-to one decimal point.

Code:

Sub Round_Ex2()
  Dim roundNumber As Double
  roundNumber = 23.98
  MsgBox "The number rounded is: " & Round(roundNumber, 1)

End Sub

Function in excel Example2.5

Step 5: Let’s hit F5 or the Run button to run this code and see the output.

Round Example 2.2

You can see an output as shown in the screenshot above. Please note that with the logic of “round to even”, the last decimal is rounded to 10 and the next decimal becomes 10 itself, due to which the number is rounded to the closest even part of the integer (i.e. 24).

Example #3 – Round Cell Value Using VBA Round

Suppose the value you wanted to round is stored in one cell of your excel worksheet.

image of round function

All you want is to round this value up-to two decimal places.

Step 1: Define a new sub-procedure in a Module to store the macro.

Code:

Sub Round_Ex3()

End Sub

 Function in excel Example 3

Step 2: Write command as “Range (“A2”).Value =”. This command works as a location where the output will be stored.

Code:

Sub Round_Ex3()

Range("A2").Value =

End Sub

Function in excel Example 3.2

Step 3: Now, use a round function to round the value present in cell A1 and store the result in cell A2. Write the following piece of code: Round (Range (“A1”).Value, 2).

Code:

Sub Round_Ex3()

Range("A2").Value = Round(Range("A1").Value, 2)

End Sub

 Function in excel Example 3.3.png

Step 4: Hit F5 or Run button to run this code and see the output in cell A2 of your worksheet.

Function Example 3 Gif

Example #4 – Round a Number Using VBA RoundUp Function

Suppose, you want to round a number up using VBA. You can do that by using WorksheetFunction.RoundUp function.

Step 1: Define a new sub-procedure in Visual Basic Editor that can store your macro.

Code: 

Sub Round_Ex4()

End Sub

Function in excel Example 4.1.png

Step 2: Define two variables, one to hold the number you wanted to round up. And the other to store the roundup result.

Code:

Sub Round_Ex4()

  Dim numToRound As Double
  Dim numRoundUp As Double

End Sub

 Function in excel Example 4.3

Step 3: Store a value into variable numToRound which you wanted to round up.

Code:

Sub Round_Ex4()

  Dim numToRound As Double
  Dim numRoundUp As Double
  numToRound = 12.7543712

End Sub

Function in excel Example 4.4

Step 4: Now, use RoundUp to roundup this number and store the result in a numRoundUp variable.

Code:

Sub Round_Ex4()

  Dim numToRound As Double
  Dim numRoundUp As Double
  numToRound = 12.7543712
  numRoundUp = Application.WorksheetFunction.RoundUp(numToRound, 4)

End Sub

 Function in excel Example 4.5

Step 5: Use MsgBox to show the output under the message box.

Code:

Sub Round_Ex4()

  Dim numToRound As Double
  Dim numRoundUp As Double
  numToRound = 12.7543712
  numRoundUp = Application.WorksheetFunction.RoundUp(numToRound, 4)
  MsgBox "The number rounded up is: " & numRoundUp

End Sub

Round Function in excel Example 4.6.png

Step 6: Hit F5 or Run button to run this code and see the output.

Round Example 4 Gif

Example #5 – Round down a Number Using VBA RoundDown Function

Step 1: In a new sub-procedure, define two new variables with the name numToRoundDown and roundDownNum. One to hold the value of the number to be rounded down and others to store the output after the number is rounded down.

Code:

Sub Round_Ex5()

  Dim numToRoundDown As Double
  Dim roundDownNum As Double

End Sub

Round Function in excel Example 5.1.png

Step 2: Assign value you want to be rounded down to the variable named “numToRoundDown”.

Code:

Sub Round_Ex5()

  Dim numToRoundDown As Double
  Dim roundDownNum As Double
  numToRoundDown = 7.075711

End Sub

Round Function in excel Example 5.2

Step 3: Now, use RoundDown to roundup this number and store the result in a roundDownNum variable.

Code:

Sub Round_Ex5()

  Dim numToRoundDown As Double
  Dim roundDownNum As Double
  numToRoundDown = 7.075711
  roundDownNum = Application.WorksheetFunction.RoundDown(numToRoundDown, 4)

End Sub

Round Function in excel Example 5.3

Step 4: Use MsgBox function to show up the value of a number rounded down.

Code:

Sub Round_Ex5()

  Dim numToRoundDown As Double
  Dim roundDownNum As Double
  numToRoundDown = 7.075711
  roundDownNum = Application.WorksheetFunction.RoundDown(numToRoundDown, 4)
  MsgBox "The number rounded down is: " & roundDownNum

End Sub

Round Function in excel Example 5.4

Step 5: Hit F5 or Run button to run this code and see the output as a message box.

Round Example 5

This is it in the article. We have captured the concepts of VBA Round, Round Up and Round Down with a handful of examples.

Things to Remember

  • This function uses a Banker’s rounding method to round the numbers which are somewhat different than the actual rounding method.
  • This function is used to round a number with a floating point or a number with fixed-decimals up-to specified number of places.
  • It means the function will round up or down the number depending upon the number after decimal points.
  • Argument decimal_places must be greater than or equal to zero.
  • If decimal_places is left blank, it will be considered as zero and the number will then be rounded to the nearest integer.
  • If decimal_places is set less than zero, then run time error 5 occurs. “Run-time error ‘5’: Invalid procedure call or argument”.
  • It is not really predictable to what this function will round the value when the digit after the decimal is 5.
  • If one or both the argument of Round function is non-numeric, then the function will return run time 13 error. “Run-time error ’13’: Type mismatch”.

Recommended Articles

This has been a guide to VBA Round Function. Here we have discussed how to use Excel VBA Round Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA On Error
  2. VBA Number Format
  3. VBA VLOOKUP
  4. VBA Function

В этом учебном материале вы узнаете, как использовать 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.

Понравилась статья? Поделить с друзьями:
  • Vba excel этот объект
  • Vba excel функция msgbox
  • Vba excel функция mid
  • Vba excel этот лист
  • Vba excel это впр