MS Access奇怪的数字

问题描述 投票:0回答:1

我从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 

我不明白为什么dblTotal4,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
vba forms ms-access double
1个回答
0
投票

Tim Williams回答了您的问题。但是,除了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
© www.soinside.com 2019 - 2024. All rights reserved.