Date value subtraction producing wrong error

后端 未结 2 1497
鱼传尺愫
鱼传尺愫 2021-01-27 10:05

I am using the below code to show the date difference in Day:Hour:Minute format.

 Function TimeSpan(dt1, dt2) 

    Dim seconds,minutes,hours,days

    If (isDat         


        
相关标签:
2条回答
  • 2021-01-27 10:06

    Try my answer from an earlier post in your UDF as the following: This answer is in VBA

    Please declare all variables and force yourself to declare by adding option explicit :)

    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 Output:

    enter image description here

    But I really suggest you to use Excel sheet functions if you have the freedom and possibility to do so.


    If date difference is more than 31 days

    Then use the solution as per this article Incorporate the DateDiff to the UDF.

    0 讨论(0)
  • 2021-01-27 10:25

    Be aware I'm more used to write VBA, so you might need to tweak here and there.

    Alternatively you could just subtract the two dates from eachother as numerical value:

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

    Now the Timespan would be (dont use "d" as that would not include months and years that could have passed):

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

    If the direction (positive or negative) of the Timespan is relevant you could change the last line into:

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

    For your time formatting issue either:

    1. Set the number format of the output cell to Text, or
    2. Add a single quote in front of the rest of the string:

       Timespan = "'" & Sgn(dblDateDiff) * Int(dblDateDiff) & ":" & Hour(dblDateDiff) & ":" & Minute(dblDateDiff)
      
    0 讨论(0)
提交回复
热议问题