Rounding in VBA
Round()
We will introduce the and functions
in VBA through examples RoundUp()
.
Round()
Using the or RoundUp()
function
in VBA
When working with Excel worksheets containing numbers and calculations, we get results that are fractions. Sometimes we have to convert these decimal numbers into whole numbers.
VBA provides three different functions that you can use to convert decimal numbers to integers. We will discuss two functions in this article.
Round()
Rounds a decimal number to the nearest integer. For example, we will store a decimal number and then use Round()
the function.
Sample code:
# VBA
Sub roundFunc()
Dim num As Double
num = 5.79
MsgBox Round(num)
End Sub
Output:
We can even mention the number of decimal places until we want to round. Let's try to round the same number to one decimal place.
Sample code:
# VBA
Sub roundFunc()
Dim num As Double
num = 5.79
MsgBox Round(num, 1)
End Sub
Output:
From the above results, we can easily round the decimal point to one decimal place. We can also use this function to round the value of a cell in an Excel worksheet.
Let's try to round numbers in an Excel worksheet using the range method.
Sample code:
# VBA
Sub roundFunc()
Range("A1").Value = Round(Range("A1").Value, 1)
End Sub
Output:
Let's discuss another function which can round a decimal number even if the number is close to a smaller integer. There may be many situations where we have to always round a decimal number to an integer greater than the decimal number.
grammar:
# VBA
Application.WorksheetFunction.RoundUp(num, 1)
Let's take an example and try using RoundUp()
the function.
Sample code:
# VBA
Sub roundFunc()
Dim num As Double
num = 5.468
MsgBox Application.WorksheetFunction.RoundUp(num, 1)
End Sub
Output:
This way, we can use RoundUp()
the function to round a number to the largest integer possible.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Remove duplicates in VBA
Publish Date:2025/04/16 Views:104 Category:Vba
-
We will explain how to remove duplicates in VBA by example. Remove duplicates in VBA When working with an Excel worksheet that contains a lot of data, it is likely that this data contains some duplicates. Any duplicates must be removed to a