vba - Excel VBA 如何将 double 舍入为整数?

标签 vba excel

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

这是我正在使用的代码:

Sub testTypes()

Dim test1 As Integer
test1 = 0.5

Debug.Print test1

End Sub

我故意尝试使用 double 字类型,以了解 VBA 如何将它们舍入(向上或向下)以使它们成为整数(假定数字以 0.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

关于vba - Excel VBA 如何将 double 舍入为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46850958/

相关文章:

java - 使用 Apache POI 库读取 Excel (xlsx) 文件会引发 NullPointerException

excel - 将值插入 Excel 单元格而不是公式

PowerPoint的vba代码

Java实现多线程(excel处理)

excel - 使用 selenium 检查域

arrays - 获取 2 个输入日期之间的月份名称并将它们放入数组中

excel - 如何将 excel 值导入 Selenium IDE

python - 如何使用 python 获取 xlsx 文件中给定单元格的 RGB 值?

excel - 使用 VBA 代码将 Excel 表转换为 Json 格式会导致时间列发生不必要的格式更改

excel - 从 excel 前端访问数据更新