0

我正在使用以下代码以 Day:Hour:Minute 格式显示日期差异。

 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

你能解释一下为什么会这样吗?

谢谢

4

2 回答 2

1

尝试我在您的UDF中较早的帖子中的回答如下:此答案在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 输出:

在此处输入图像描述

但如果你有自由和可能的话,我真的建议你使用 Excel 工作表函数。


如果日期差异超过 31 天

然后使用本文中的解决方案将 合并DateDiff到 UDF 中。

于 2012-12-12T10:16:16.640 回答
1

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

或者,您可以将两个日期从彼此中减去作为数值:

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

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

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

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

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

对于您的时间格式问题:

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

     Timespan = "'" & Sgn(dblDateDiff) * Int(dblDateDiff) & ":" & Hour(dblDateDiff) & ":" & Minute(dblDateDiff)
    
于 2012-12-12T10:24:07.137 回答