Excel VBA如何将整数翻倍?

我试图理解在VBA中声明错误类型的变量时可能发生的错误类型.

这是我正在使用的代码:

Sub testTypes()

Dim test1 As Integer
test1 = 0.5

Debug.Print test1

End Sub

我试图使用双号类型来查看VBA如何围绕它们(向上或向下)使它们成为一个整数,因为数字结束于.5

我得到了令人费解的结果:

5.567 --> 6
5.5 --> 6
4.5 --> 4
3.5 --> 4
2.5 --> 2
1.5 --> 2
0.5 --> 0

任何人都可以解释Excel如何确定它是向上还是向下舍入?

最佳答案 为了避免所谓的银行家舍入(=中点值5总是四舍五入到最接近的偶数)你可以使用

>(1)WorkSheetFunction.Round
>(2)用户定义的函数.

银行家的舍入是用于财务和统计操作的标准舍入形式,以便通过在单个方向上始终舍入中点值来最小化多个舍入操作的重大舍入误差.

(1)使用WorksheetFunction Round()的示例

Sub RoundWithWorkSheetFunction()
' Purpose: avoid so called bankers' rounding in VBA (5 always rounds even)
With WorksheetFunction
    Debug.Print "WorksheetFunction.Round(3.5, 0)=" & .Round(3.5, 0), ":| VBA rounds to " & Round(3.5, 0)
    Debug.Print "WorksheetFunction.Round(4.5, 0)=" & .Round(4.5, 0), ":| VBA rounds to " & Round(4.5, 0)
End With

End Sub

(2)工作表功能的替代方案(避免银行家的舍入):

Function roundIt(ByVal d As Double, ByVal nDigits As Integer) As Double
' Purpose: avoid so called bankers' rounding in VBA (5 always rounds even)
If nDigits > 0 Then
   ' if continental european colon instead of point separartor
   ' roundIt= val(Replace(Format(d, "0." & String(nDigits, "0")), ",", "."))
     roundIt = Val(Format(d, "0." & String(nDigits, "0")))
Else
   ' if continental european colon instead of point separartor
   ' roundIt =  val(Replace(Format(d / (10 ^ nDigits), "0."), ",", "."))
   roundIt = Val(Format(d / (10 ^ nDigits), "0."))
End If
End Function
点赞