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

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

我很困惑如何使用VBA中的FORMAT()函数将C2的值转换为秒? 还有其他的function比FORMAT更好吗? 基本上我很困惑Excel的date序列值和他们代表什么。

代码如下

编辑:感谢大家的回应。 下面的两个答案为我正在尝试做的工作。

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 

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

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

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

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

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

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

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

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中处理date和时间的信息。 理解date在VBA上下文中的工作是不同的,并且有自己独特的用于操作的语法函数集是很重要的。

第二编辑:这个清洁版本将是:

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

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

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

 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 

有关定时器function的文档

在你的程序的第一行获取date(不需要格式):

 Dim startTime as Date startTime = Now() 

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

 Dim endTime as Date endTime = Now() 

然后使用DateDiff

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

我通常如何去吹嘘我的过程时间给用户

 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