How to calculate the time difference in VBA

kato01

Board Regular
Joined
Sep 9, 2005
Messages
81
Hello,

I am trying to calculate the time difference between two times defined by date and time
I need some help since, the result I get does not seem to be correct.
Please c]see code below.
What am I missing?

Thank you


VBA Code:
Sub time_difference()

D1 = "08/26/23"
T1 = "13:19"
D2 = "08/27/23"
T2 = "04:48"
dt1 = D1 + " " + T1
dt2 = D2 + " " + T2
DIF_S = DateDiff("n", dt1, dt2)
DIF_M = Int(DIF_S / 60)
DIF_S = DIF_S - DIF_M * 60
DIF_H = Int(DIF_M / 60)
DIF_M = DIF_M - DIF_H * 60
Debug.Print i, D2, T2, D1, T1, DateDiff("n", dt1, dt2), DIF_H, DIF_M, DIF_S

end sub
 

Excel Facts

What do {} around a formula in the formula bar mean?
{Formula} means the formula was entered using Ctrl+Shift+Enter signifying an old-style array formula.
Does this help at all ?
VBA Code:
Option Explicit

Sub my_time_difference()
Dim D1 As String, T1 As String, D2 As String, T2 As String
Dim dt1 As Date, dt2 As Date, diff As Date

D1 = "08/26/23"
T1 = "13:19"
D2 = "08/27/23"
T2 = "04:48"

dt1 = D1 & " " & T1
dt2 = D2 & " " & T2

diff = dt2 - dt1

'Debug.Print diff
Debug.Print CLng(Int(diff)) & " days"
Debug.Print Hour(diff) & " hours"
Debug.Print Minute(diff) & " minutes"
Debug.Print Second(diff) & " seconds"

End Sub
 
Upvote 1
Solution

Forum statistics

Threads
1,223,911
Messages
6,175,337
Members
452,637
Latest member
Ezio2866

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top