[英]Calculate Time Difference in excel VBA and show results by the minute
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.问题是如果我计算 6:30 和 8:00,结果是 2 小时 30 分钟,这是错误的。
Thanks in Advance.提前致谢。
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
You can use Format()
for this:您可以为此使用
Format()
:
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.