这question has already been asked for the C++ language但我需要一个VBA功能。我尝试将C ++函数转换为VBA,但它没有返回正确的值。
我需要一个执行以下操作的功能:
RoundUp(23.90, 5)
'return 25
RoundUp(23.90, 10)
'return 30
RoundUp(23.90, 20)
'return 40
RoundUp(23.90, 50)
'return 50
RoundUp(102.50, 5)
'return 105
RoundUp(102.50, 20)
'return 120
这是我到目前为止所拥有的。它大部分时间都有效,但对于小于0.5的数字,返回的值不正确。因此问题似乎是我如何计算余数值的舍入问题。
Public Function RoundUp(dblNumToRound As Double, lMultiple As Long) As Double
Dim rmndr As Long
rmndr = dblNumToRound Mod lMultiple
If rmndr = 0 Then
RoundUp = dblNumToRound
Else
RoundUp = Round(dblNumToRound) + lMultiple - rmndr
End If
End Function
例如:
RoundUp(49.50, 50)
'Returns 49.50 because rmndr = 0
答案 0 :(得分:4)
我只是除以lMultiple
,向上舍入并再次乘以。
假设你确实想要整理(也是负数):
Public Function RoundUp(dblNumToRound As Double, lMultiple As Long) As Double
Dim asDec as Variant
Dim rounded as Variant
asDec = CDec(dblNumToRound)/lMultiple
rounded = Int(asDec)
If rounded <> asDec Then
rounded = rounded + 1
End If
RoundUp = rounded * lMultiple
End Function
我实际上并不是VBA程序员,所以这可能需要一个或两个调整过的逗号。但重要的是:
答案 1 :(得分:0)
更简单的解决方案是在舍入前为数字添加.5:
1.1 -> Round(1.1+.5, 0) -> 2