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

时间:2014-12-01 15:11:27

标签: excel vba excel-vba datetime runtime

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

我很困惑如何使用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

5 个答案:

答案 0 :(得分: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

结果应写在例程结束时。

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

Documentation on the timer function

答案 1 :(得分:4)

DateDiff()正是您要找的。 " s"定义您正在寻找以秒为单位的差异。

Worksheets("Table").Range("C2").Value = DateDiff("s", Worksheets("Table").Range("A2").Value, Worksheets("Table").Range("B2").Value)

编辑:http://www.likeoffice.com/28057/excel-date了解有关在Excel VBA中使用日期和时间的详细信息。重要的是要理解日期在VBA的上下文中的工作方式不同,并且有自己独特的语法函数集来进行操作。

第二次编辑:更简洁的版本是:

StartDateTime = Now()
'Run Code
Worksheets("Table").Range("C2").Value = DateDiff("s", StartDateTime, Now())

答案 2 :(得分:3)

在程序的第一行获取日期(无需格式化):

Dim startTime as Date
startTime = Now()

在程序结束时,再次获取日期:

Dim endTime as Date
endTime = Now()

然后使用DateDiff

Dim timeInSeconds as long
timeInSeconds = DateDiff("s", startTime, endTime)

答案 3 :(得分:2)

有几种方法可以使用VBA格式化单元格/变量。

没有特别的顺序,首先你可以使用NumberFormat属性格式化范围,可以这样使用:

Worksheets("Table").Range("C2").Value = Now()
Worksheets("Table").Range("C2").NumberFormat = "ss"

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

Worksheets("Table").Range("C2").Value = Format(Now(), "ss")

请参阅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

答案 4 :(得分:0)

我通常如何向用户吹嘘我的处理时间

Sub Process()
Dim startTime as Date
Dim endTime as Date

startTime = Now

'Logic for what your process must do

endTime = Now

MsgBox "Process completed in : " & Format(endTime - startTime, "hh:mm:ss")

End Sub