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
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:
But I really suggest you to use Excel sheet functions if you have the freedom and possibility to do so.
Then use the solution as per this article
Incorporate the DateDiff
to the UDF.
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:
Add a single quote in front of the rest of the string:
Timespan = "'" & Sgn(dblDateDiff) * Int(dblDateDiff) & ":" & Hour(dblDateDiff) & ":" & Minute(dblDateDiff)