Im looking for a way to calculate the time difference between two text box with time/ date value. Here is what i have :
Sub Calculatediff()
Dim date1 As Date
Dim date2 As Date
Dim totalminutes As Integer
date1 = Worksheets("Sheet2").TextBox1.Value
date2 = Worksheets("Sheet2").TextBox2.Value
totalminutes = DateDiff("n", date1, date2)
Dim hours As Integer
hours = totalminutes / 60
Dim minutes As Integer
minutes = (totalminutes Mod 60)
Dim sMessage
sMessage = totalminutes & " minutes = " & hours & " hours " & minutes & " minutes"
MsgBox sMessage, vbInformation, "Information"
End Sub
The problem is if i calculate 6:30 & 8:00 the result is 2 Hours and 30 Minutes which is wrong.
Thanks in Advance.
CodePudding user response:
You can use Format()
for this:
Dim d1 As Date, d2 As Date
d1 = [F20] 'dat-time in F20 and F21
d2 = [f21]
'need to escape d, h, m, s, n in the format string with with "\"
Debug.Print Format(d2 - d1, "h \hour\s a\n\d m \mi\nute\s")
CodePudding user response:
I was able to get my desired results as per the below :
Sub A()
Dim EDay As Date
Dim ETime As Date
Dim DtgA As Date
Dim FMessage
EDay = Format(CDate(Replace(Worksheets("Calculate Time").Range("D4").Value, ".", "/")), "dd-mmm-yyyy")
ETime = Format(Worksheets("Calculate Time").TextBox13.Value, "hh:mm:ss")
DtgA = EDay ETime
Dim EDay2 As Date
Dim ETime2 As Date
Dim DtgB As Date
EDay2 = Format(CDate(Replace(Worksheets("Calculate Time").Range("G4").Value, ".", "/")), "dd-mmm-yyyy")
ETime2 = Format(Worksheets("Calculate Time").TextBox14.Value, "hh:mm:ss")
DtgB = EDay2 ETime2
Dim result As Date
result = Format(DateDiff("s", DtgA, DtgB) / (60 * 60) / 24, "hh:mm:ss")
'MsgBox "Date 1: " & DtgA & vbNewLine & "Date 2: " & DtgB & vbNewLine & vbNewLine & DateDiff("s", DtgA, DtgB) / (60 * 60) & vbNewLine & result
FMessage = DateDiff("s", DtgA, DtgB) / (60 * 60) & " Hours"
Worksheets("Calculate Time").TextBox16.Value = FMessage
End Sub