Calculate Time Difference between two times in hours minutes seconds with VBA

In many situations with different begin and end timings we may wish to automate our calculations of the difference in hours, minutes and seconds. This can be done quickly and easily with Excel VBA.

Watch the training video:

Watch the vide on YouTube.

Here’s the complete VBA code to calculate time difference between two timings:

Sub timeDifference()
Dim lastrow As Long
lastrow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastrow
‘We calculate the total hours
Cells(i, 3) = DateDiff(“s”, Cells(i, 1), Cells(i, 2)) / (60 * 60)
‘here we get the integer value and ignore the fraction
Cells(i, 3) = Int(Cells(i, 3))
‘we use the fraction hours to calculate the minutes
Cells(i, 4) = DateDiff(“s”, Cells(i, 1), Cells(i, 2)) / 60 – Cells(i, 3) * 60
‘we get the integer value of the minutes
Cells(i, 4) = Int(Cells(i, 4))
‘we determine the fraction value of the minutes
Cells(i, 5) = DateDiff(“s”, Cells(i, 1), Cells(i, 2)) / 60 – Cells(i, 3) * 60 – Cells(i, 4)
‘ we convert the fraction minutes into seconds
Cells(i, 5) = Cells(i, 5) * 60
Next
End Sub
Further reading:

Leave a Reply

Your email address will not be published. Required fields are marked *