首页 > 解决方案 > MS Access 奇怪的数字

问题描述

我从 VBA 中的一个函数收到奇怪的数字。

我有连续表格,其中是一个按钮,用户可以从中操作文本框中的小时数。此文本框位于表单页脚中。

我的代码是这样的:

Private Sub Option39_Click()
    Dim time As Double

    'calculate time to format
    time = 25 / 24

    If Option39.Value = True Then
         Debug.Print dblTotal
        dblTotal = dblTotal + time
         Debug.Print dblTotal
        Me.txtTotalTeamTotal = FormatUnlimitedHours(dblTotal)
         Debug.Print dblTotal
    Else
        dblTotal = dblTotal - time
        Me.txtTotalTeamTotal = FormatUnlimitedHours(dblTotal)
    End If
End Sub

从 debug.print 我收到这些值

3,66611111111111 
4,70777777777778 
112,986666666667 

我不明白为什么dblTotal改变它的价值4,70777777777778 to 112,986666666667为什么改变了数字?

FormatUnlimitedHours() 函数定义如下:

Public Function FormatUnlimitedHours(time As Variant) As Variant
    'function that can have unlimited number of hours in hh:mm:ss format
    Dim comma As Integer
    Dim hours As Variant
    Dim minutes As Variant
    'switch to hours format
    time = time * 24

    If time > 23 Then

        comma = InStr(time, ",") - 1

        If Not comma < 0 Then
            minutes = "0," & Mid(time, comma + 2, Len(time) - comma + 1)
            minutes = format(minutes / 24, "hh:mm:ss")
            hours = CDbl(Left(time, comma)) + CDbl(Left(minutes, InStr(minutes, ":") - 1))
            FormatUnlimitedHours = hours & ":" & Mid(minutes, InStr(minutes, ":") + 1, 5)
            Exit Function
        Else
            'for whole numbers
            FormatUnlimitedHours = time & ":00:00"
            Exit Function
        End If

    End If

    FormatUnlimitedHours = format(time / 24, "hh:mm:ss")

End Function

dblTotal 的初始值在表单加载时定义

Private Sub Form_Load()

    dblTotal = DSum("sumOfTotalTime", "QueryTime")

End Sub

标签: vbaformsms-accessdouble

解决方案


蒂姆威廉姆斯已经回答了你的问题。但是,您决不能将日期和时间当作 DateTime 以外的任何东西来处理。它只会使事情复杂化。

例如,在大多数英语国家,逗号不是小数分隔符,而 DateTime 的“基本”类型是 Double,因此通常在 DateTime 和 Double 之间来回转换没有区别。

下面是一个遵循这些规则的类似函数的示例 - 这也使它更简单:

Public Function FormatHourMinuteSecond( _
  ByVal datTime As Date, _
  Optional ByVal strSeparator As String = ":") _
  As String

' Returns count of days, hours, minutes, and seconds of datTime
' converted to hours, minutes, and seconds as a formatted string
' with an optional choice of time separator.
'
' Example:
'   datTime: #10:03:55# + #20:01:24#
'   returns: 30:05:19
'
' 2014-06-17. Cactus Data ApS, CPH.

  Dim strHour       As String
  Dim strMinuteSec  As String
  Dim strHours      As String

  strHour = CStr(Fix(datTime) * 24 + Hour(datTime))
  ' Add leading zero to minute and second count when needed.
  strMinuteSec = Right("0" & CStr(Minute(datTime)), 2) & strSeparator & Right("0" & CStr(Second(datTime)), 2)
  strHours = strHour & strSeparator & strMinuteSec

  FormatHourMinuteSecond = strHours

End Function

例子:

? FormatHourMinuteSecond(25 / 24)
25:00:00

推荐阅读