如何在Excel中正确将秒转换为hh:mm:ss

5

我正在尝试计算在Excel中完成分析所需的时间。我使用DateDiff来计算所需的秒数,然后尝试将其格式化为小时、分钟和秒。

我的代码如下,在以下行中导致溢出错误:

dTime = dTime / (60 * 60 * 24)

你知道我做错了什么吗?

Dim dTime As Long
Dim startTime, endTime As Date

startTime = Now() ' at the start of the analysis
endTime = Now() ' at the end of the analysis

dTime = DateDiff("s", startTime, endTime)
dTime = dTime / (60 * 60 * 24) 'convert seconds into days
StatusBox.Value = "Analysis completed in " & Format(dTime, "hh:mm:ss") & "."

3
你可能需要一个双精度型变量dTime。 - MatthewD
1
这里将startTime声明为变量。您需要明确指出:Dim startTime as Date - kaybee99
4个回答

8

看起来你过度补偿了。不需要进行转换。只需从结束时间减去开始时间(可选择存储为double,如@MatthewD所述),并将单元格格式化为hh:mm:ss(首选)或表示时间的字符串 Format(dTime, "hh:mm:ss")

Dim dTime As Double
Dim startTime As Date, endTime As Date

startTime = Now() ' at the start of the analysis
'analysis here
endTime = Now() ' at the end of the analysis

dTime = endTime - startTime 
StatusBox.Value = "Analysis completed in " & Format(dTime, "hh:mm:ss") & "."

如果您想将startTime声明为日期类型变量,则声明方式不正确。您使用的方法将其创建为变体。


3

试试这个

Sub seconds()
Dim dTime As Variant
Dim startTime, endTime As Date

startTime = #8/7/2015 10:43:32 PM# ' at the start of the analysis
endTime = Now() ' at the end of the analysis

dTime = DateDiff("s", startTime, endTime)
dTime = dTime / 86400
MsgBox "Analysis completed in " & Format(dTime, "hh:mm:ss") & "."

End Sub

0

试试这个

Dim startTIME, endTIME, totalTIME As Double

startTIME = Timer

'Your code Here

endTIME = Timer
  totalTIME = Round(endTIME - startTIME, 2)
MsgBox "Process completed successfuly in " & Int(totalTIME / 60) & " minutes, " & totalTIME Mod 60 & " seconds.", vbInformation

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

0

我知道已经有一段时间了,但这仍然是一个相关的问题。 @Jason,在声明变量时,你需要为每个单独的变量设置类型,否则它会默认设置为变体(Variant)。

Sub CalculateDuration()
Dim startTime As Date, endTime As Date

startTime = now                         'start of the analysis

'insert your code here

endTime = now                           'end of the analysis

Debug.Print "Analysis completed in " & Format(endTime - startTime, "hh:mm:ss") & "."
End Sub

或者您也可以使用DateDiff来计算开始日期和结束日期之间的差异。请确保将DateDiff的结果除以86400(24小时内的秒数)。

Debug.Print "Analysis completed in " & Format(DateDiff("s", startTime, endTime) / 86400, "hh:mm:ss") & "."

DateDiff 在这里可能有点过度,其实你并不需要它。但如果你偏爱使用,下面的设置可能会很有用。将 (DateDiff("s", startTime, endTime) 中的 "s" 替换为以下参数:

参数(说明)

  • yyyy(年)
  • q(季度)
  • m(月)
  • y(年中的第几天)
  • d(日)
  • w(工作日)
  • ww(周)
  • h(小时)
  • n(分钟)
  • s(秒)

希望能对你有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接