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

我正在计算在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") & "." 

看来你是过度补偿。 没有转换是必要的。 简单地从结束时间中减去开始时间(可选地以@MatthewD的forms存储为double),并将单元格格式化为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声明是不正确的,如果你想它是一个datetypesvar。 您正在使用的方法创build它作为一个变种。

尝试这个

 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