如何在VBA中加小时,分钟,秒

How to add up hours, mins, seconds in VBA

提问人:ravens23 提问时间:11/15/2023 更新时间:11/15/2023 访问量:67

问:

我有代码可以获取具有不同持续时间的列。格式为“hh:mm:ss”。我需要将所有这些加起来(将超过 24 小时),并在最后以相同的格式获得总数。有没有办法在VBA中做到这一点?

standbyTime = CDate(ThisWorkbook.Worksheets("Sheet1").Cells(dateCell.Row, "U").Value)
failureTime = CDate(ThisWorkbook.Worksheets("Sheet1").Cells(dateCell.Row, "W").Value)
powerOffTime = CDate(ThisWorkbook.Worksheets("Sheet1").Cells(dateCell.Row, "X").Value)
                        
If (ThisWorkbook.Worksheets("Sheet1").Cells(dateCell.Row, "W").Value <> "") Then
   operationalTime = TimeValue(failureTime) - TimeValue(standbyTime)
Else
   operationalTime = TimeValue(powerOffTime) - TimeValue(standbyTime)
End If
                        
totalTime = totalTime + operationalTime

此代码将随时间推移而滚动。

输出需要看起来像 100:35:20

有什么想法吗?

Excel VBA

评论

3赞 GSerg 11/15/2023
The format is "hh:mm:ss"- 好吧,让它.[hh]:mm:ss
0赞 Tragamor 11/15/2023
@GSerg这是一个很好的提示!作为参考,使用这种格式,您可以将电子表格中的所有时间值相加,并用它设置输出字段,因此不需要VBA。
0赞 ravens23 11/15/2023
@GSerg 格式化前如何将时间相加?它似乎没有按预期工作。在进行添加之前,我应该每次都格式化为该格式吗?
0赞 ravens23 11/15/2023
@Tragamor 那里还有一些其他代码(对我来说)在 VBA 中更容易完成,而不是作为公式
0赞 GSerg 11/15/2023
就像你现在把它们加起来一样,作为日期。(并不是说你在代码中做对了,如果日期属于不同的日期,你会得到错误的结果。

答:

-1赞 Red Hare 11/15/2023 #1

举个例子:

enter image description here

假设您在单元格中有这些值,那么代码将是:

Sub SumTimes()
Dim d As Double
Dim w As Worksheet
Set w = ThisWorkbook.Worksheets("Sheet1")
d = w.Range("b2").Value2 + w.Range("b3").Value2 + w.Range("b4").Value2 ' be aware of value2
Dim h As Long, m As Long, s As Long
h = Fix(d * 24) ' hours
m = Fix(d * 1440) - h * 60 ' Minutes
s = Fix(d * 86400) - h * 3600 - m * 60 ' Seconds

MsgBox h & ":" & m & ":" & s

End Sub

确保使用 Value2