问题描述
我正在尝试计算以周为单位的日期差异。我实际上想要一个最接近小数点后 10 位 (0.0) 的答案。计算正在截断或四舍五入我的结果。如何获得更准确的答案?代码如下
Option Explicit
Sub DateTesting()
Dim Date1 As Date
Dim Date2 As Date
Dim DaysDiffer As Long
Dim WeeksDiffer As Long
Date1 = "1/10/2021"
Date2 = "7/14/2021"
DaysDiffer = DateDiff("d",Date1,Date2)
MsgBox DaysDiffer
'185 is the result
WeeksDiffer = DaysDiffer / 7
' 185/7= 26.4285
MsgBox WeeksDiffer
' 26 is the result
' Why am I getting a truncated integer value for the calculation of Weeks???
End Sub
解决方法
以下是获取四舍五入的小数周的方法:
Sub DateTesting()
Dim Date1 As Date
Dim Date2 As Date
Dim DaysDiffer As Long
Dim WeeksDiffer As Double
Date1 = #1/10/2021#
Date2 = #7/14/2021#
DaysDiffer = DateDiff("d",Date1,Date2)
MsgBox DaysDiffer
' 185 is the result
WeeksDiffer = DaysDiffer / 7
' 26.4285714285714 is the result
MsgBox Format(WeeksDiffer,"0.0")
' 26.4 is the rounded result
End Sub
有关各种日期处理,请参阅 VBA.Date。
关于高精度四舍五入,请参见VBA.Round。