提问人:ravens23 提问时间:11/15/2023 更新时间:11/15/2023 访问量:67
如何在VBA中加小时,分钟,秒
How to add up hours, mins, seconds in VBA
问:
我有代码可以获取具有不同持续时间的列。格式为“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
有什么想法吗?
答:
-1赞
Red Hare
11/15/2023
#1
举个例子:
假设您在单元格中有这些值,那么代码将是:
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
评论
The format is "hh:mm:ss"
- 好吧,让它.[hh]:mm:ss