日期值减法产生错误的错误

时间:2012-12-12 09:50:36

标签: excel vbscript

我使用以下代码显示日期:小时:分钟格式的日期差异。

 Function TimeSpan(dt1, dt2) 

    Dim seconds,minutes,hours,days

    If (isDate(dt1) And IsDate(dt2)) = false Then 
        TimeSpan = "00:00:00" 
        Exit Function 
    End If 

    seconds = Abs(DateDiff("S", dt1, dt2)) 
    minutes = seconds \ 60 
    hours = minutes \ 60 
    days  = hours \ 24
    minutes = minutes mod 60 
    seconds = seconds mod 60 
    days    = days    mod 24 

    if len(hours) = 1 then hours = "0" & hours 

    TimeSpan = days& ":" & _ 
        RIGHT("00" & hours , 2) & ":" & _ 
        RIGHT("00" & minutes, 2) 
End Function 

但它并没有为某些情况产生预期值。

  D1=#9/24/2012  8:09:15 AM# and D2=#9/25/2012  8:09:15 AM# gives correct data like 1:24:00 whereas below are producing error when working with VBScript and Excel.
  D1=#9/5/2012  8:45:43 AM# and D2=#9/25/2012  8:45:43 AM# result=0.888888888888889
  D1=#9/6/2012  8:29:34 AM# and D2=#9/17/2012  8:59:36 AM# result=0.503125

你能解释一下原因吗?

由于

2 个答案:

答案 0 :(得分:1)

UDF 中尝试我的answer from an earlier post,如下所示:此答案位于 VBA

请声明所有变量并强制通过添加明确选项来声明:)

option explicit
Function TimeSpan(dt1 As Date, dt2 As Date) As String
Dim dtTemp As Date

    Application.ScreenUpdating = False
        If (IsDate(dt1) And IsDate(dt2)) = False Then
            TimeSpan = "00:00:00"
            Exit Function
        End If

        If dt2 < dt1 Then
            dtTemp = dt2
            dt2 = dt1
            dt1 = dt2
        End If
        '-- since you only had days, I have put up to days here. 
        '-- if you require months, years you may use yy:mm:dd:hh:mm:ss
        '-- which is pretty self-explainatory ;)
        TimeSpan = Application.WorksheetFunction.Text((dt2 - dt1), "dd:hh:mm:ss")

    Application.ScreenUpdating = False
End Function

UDF输出:

enter image description here

但如果您有自由和可能,我建议您使用Excel工作表功能。


如果日期差异超过31天

然后使用solution as per this articleDateDiff合并到UDF。

答案 1 :(得分:1)

请注意,我更习惯于编写VBA,因此您可能需要在此处进行调整。

或者你可以将彼此的两个日期减去数值:

Dim dblDateDiff as Double
dblDateDiff = Abs(dt2 - dt1)

现在时间跨度将是(不要使用“d”,因为这不包括可能已经过去的月份和年份):

Timespan = Int(dblDateDiff) & ":" & Hour(dblDateDiff) & ":" & Minute(dblDateDiff)

如果Timespan的方向(正面或负面)相关,您可以将最后一行更改为:

Timespan = Sgn(dblDateDiff) * Int(dblDateDiff) & ":" & Hour(dblDateDiff) & ":" & Minute(dblDateDiff)

您的时间格式问题:

  1. 将输出单元格的数字格式设置为文本,或
  2. 在字符串的其余部分前面添加一个引号:

     Timespan = "'" & Sgn(dblDateDiff) * Int(dblDateDiff) & ":" & Hour(dblDateDiff) & ":" & Minute(dblDateDiff)