Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Rounding functions

VBA and Custom Functions

Rounding functions

by  Craig0201  Posted    (Edited  )
A pair of rounding functions. Work identically to those in Excel.

Function Round(Number As Double, Num_Digits As Integer) As Double

'Set up variables
Dim dblNumNum_Digits As Double
Dim intNumNum_Digits As Integer

'Move decimal point such that int will perform at correct level
dblNumNum_Digits = Number * (10 ^ Num_Digits)

'Integerise
intNumNum_Digits = Int(dblNumNum_Digits)

'Compare integer to see if needs rounding up
If dblNumNum_Digits - intNumNum_Digits >= 0.5 Then
'round up
intNumNum_Digits = intNumNum_Digits + 1
Else
'round down
intNumNum_Digits = intNumNum_Digits
End If

'Return result, moving decimal point back
Round = intNumNum_Digits / (10 ^ Num_Digits)

End Function

Function MRound(Number As Double, Multiple As Double) As Double

'Set up variables
Dim dblDivided As Double
Dim dblIntDivided As Double

'Divide
dblDivided = Number / Multiple
'Integerise
dblIntDivided = Int(dblDivided)

'Round dblDivided to nearest whole number in intDivided
dblIntDivided = dblIntDivided + Round(dblDivided - dblIntDivided, 0)

'Return result, returning to nearest multiple
MRound = dblIntDivided * Multiple

End Function

Hope they help!

Craig
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top