Date value subtraction producing wrong error

后端 未结 2 1526
鱼传尺愫
鱼传尺愫 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: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)
      

提交回复
热议问题