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

aro*_*y88 7 excel datetime vba runtime excel-vba

我正在研究一个问题,我需要确定程序执行的总时间.第一行代码需要写入当前的"开始时间",最后一行代码需要写入当前的"结束时间".然后我减去"开始时间" - "结束时间"=总时间.

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

代码如下

编辑:感谢大家的回复.以下两个答案都适用于我正在尝试做的事情.

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
Run Code Online (Sandbox Code Playgroud)

che*_*eak 5

不要使用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
Run Code Online (Sandbox Code Playgroud)

结果应写在例程结束时.

With Worksheets("Table")
    .Range("A2").Value = startTime
    .Range("B2").Value = endTime 
    .Range("C2").Value = runTime
End With
Run Code Online (Sandbox Code Playgroud)

关于计时器功能的文档


Gar*_*eth 2

您可以通过多种方式使用 VBA 来设置单元格/变量的格式。

没有特定的顺序,首先您可以使用NumberFormat可应用的属性来格式化范围,如下所示:

Worksheets("Table").Range("C2").Value = Now()
Worksheets("Table").Range("C2").NumberFormat = "ss"
Run Code Online (Sandbox Code Playgroud)

另一种方法是您可以Now()使用以下Format()函数进行格式化:

Worksheets("Table").Range("C2").Value = Format(Now(), "ss")
Run Code Online (Sandbox Code Playgroud)

请参阅 Microsoft 的文档来实现不同的格式:

NumberFormathttp://msdn.microsoft.com/en-us/library/office/ff196401%28v=office.15%29.aspx Formathttp://msdn.microsoft.com/en-us/library/office/gg251755 %28v=office.15%29.aspx