vba - 如何将 VBA Now() 转换为秒以确定程序总运行时间

标签 vba excel datetime runtime

我正在解决一个问题,我需要确定程序执行所需的总时间。第一行代码需要写入当前的“开始时间”,最后一行代码需要写入当前的“结束时间”。然后我减去“开始时间”-“结束时间”= 总时间。

我很困惑如何在 VBA 中使用 FORMAT() 函数将 C2 的值转换为秒?还有其他功能比 FORMAT 更好吗?基本上我对 Excel 的日期序列值及其代表的内容感到困惑。

代码如下

编辑:感谢大家的回复。下面的两个答案都适用于我想做的事情。

sub ExecutionTime()

Worksheets("Table").Range("A2").Value = Now()

'All my executable code goes here. It's a relatively small program compiling a table so it
runs very quick. 

Worksheets("Table").Range("B2").Value = Now()
Worksheets("Table").Range("C2").Value = Worksheets("Table").Range("A2").Value - Worksheets("Table").Range("B2").Value

end Sub

最佳答案

不要使用Date数据成员或Now方法来分析程序的运行时间。相反,Timer 函数是最合适的解决方案,因为它返回代表秒的 Single。它不需要类型转换,并且产生比整数秒更准确的结果。

使用 LimaNightHawk 的答案作为模板,因为您应该将它们存储在局部变量中,而不是直接写入工作表。

Dim startTime as Single
startTime = Timer()

'  Do stuff

Dim endTime as Single
endTime = Timer()

Dim runTime as Single
runTime = endTime - startTime

结果应写在例程结束时。

With Worksheets("Table")
    .Range("A2").Value = startTime
    .Range("B2").Value = endTime 
    .Range("C2").Value = runTime
End With

Documentation on the timer function

关于vba - 如何将 VBA Now() 转换为秒以确定程序总运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27231357/

相关文章:

excel - 由 VBA 关闭的工作簿未关闭引用,IsAddin 工作簿

vba - 从另一个工作簿使用 Vlookup 时遇到问题

excel - 如何使用vba为excel表声明变量

sql-server - SQL Server,插入 Excel "Invalid column name"时出现 "linked server"错误

python - Path().stat().st_mtime 时区?

javascript - 2个日期时间时刻之间的时差

excel - 使用 VBA 正则表达式删除模式中的空格

excel - 与另一个字典一起使用时字典对象不会被删除

Excel 条件格式 - 'IF' 公式语法

python - 如何将列转换为日期时间,忽略模糊的字符串值