簡體   English   中英

計算 excel VBA 的時差並按分鍾顯示結果

[英]Calculate Time Difference in excel VBA and show results by the minute

我正在尋找一種方法來計算兩個具有時間/日期值的文本框之間的時差。 這是我所擁有的:

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

問題是如果我計算 6:30 和 8:00,結果是 2 小時 30 分鍾,這是錯誤的。

提前致謝。

在此處輸入圖像描述

我能夠按照以下方式獲得所需的結果:

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

您可以為此使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM