【问题标题】:How to correctly convert seconds to hh:mm:ss in Excel如何在 Excel 中正确将秒转换为 hh:mm:ss
【发布时间】:2015-08-07 17:03:26
【问题描述】:

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

【问题讨论】:

  • 你可能需要 dTime As Double
  • startTime 在这里被声明为变体。你需要明确:Dim startTime as Date

标签: excel vba


【解决方案1】:

看来你是过度补偿了。无需转换。只需从结束时间中减去开始时间(可选地存储为 @MatthewD 提到的双精度)并将单元格格式化为 hh:mm:ss (首选)或使用@987654321 表示时间的字符串@。

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") & "."

如果您希望它是 Date 类型的 var,则您的 startTime 声明不正确。您使用的方法将其创建为变体。

【讨论】:

    【解决方案2】:

    试试这个

    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
    

    【讨论】:

      【解决方案3】:

      试试这个

      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
      

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 2015-09-29
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多