如何在VBA(Excel)中获取以毫秒为单位的DateDiff值?

我需要计算两个时间戳之差(以毫秒为单位)。 不幸的是,VBA的DateDiff函数不提供这种精度。 有没有解决办法?

你可以使用这里描述的方法如下:

创build一个名为StopWatch的新类模块将以下代码放置在StopWatch类模块中:

 Private mlngStart As Long Private Declare Function GetTickCount Lib "kernel32" () As Long Public Sub StartTimer() mlngStart = GetTickCount End Sub Public Function EndTimer() As Long EndTimer = (GetTickCount - mlngStart) End Function 

您使用的代码如下:

 Dim sw as StopWatch Set sw = New StopWatch sw.StartTimer ' Do whatever you want to time here Debug.Print "That took: " & sw.EndTimer & "milliseconds" 

其他方法描述了VBA定时器function的使用,但是这仅仅精确到百分之一秒(厘秒)。

如果你只需要时间在Centiseconds,那么你不需要TickCount API。 您可以使用所有Office产品中的VBA.Timer方法。

 Public Sub TestHarness() Dim fTimeStart As Single Dim fTimeEnd As Single fTimeStart = Timer SomeProcedure fTimeEnd = Timer Debug.Print Format$((fTimeEnd - fTimeStart) * 100!, "0.00 "" Centiseconds Elapsed""") End Sub Public Sub SomeProcedure() Dim i As Long, r As Double For i = 0& To 10000000 r = Rnd Next End Sub 

GetTickCount和性能计数器是必要的,如果你想去微秒..毫秒,你可以使用这样的事情..

 'at the bigining of the module Private Type SYSTEMTIME wYear As Integer wMonth As Integer wDayOfWeek As Integer wDay As Integer wHour As Integer wMinute As Integer wSecond As Integer wMilliseconds As Integer End Type Private Declare Sub GetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME) 'In the Function where you need find diff Dim sSysTime As SYSTEMTIME Dim iStartSec As Long, iCurrentSec As Long GetLocalTime sSysTime iStartSec = CLng(sSysTime.wSecond) * 1000 + sSysTime.wMilliseconds 'do your stuff spending few milliseconds GetLocalTime sSysTime ' get the new time iCurrentSec=CLng(sSysTime.wSecond) * 1000 + sSysTime.wMilliseconds 'Different between iStartSec and iCurrentSec will give you diff in MilliSecs 

您也可以在单元格中使用=NOW()公式calcilated:

 Dim ws As Worksheet Set ws = Sheet1 ws.Range("a1").formula = "=now()" ws.Range("a1").numberFormat = "dd/mm/yyyy h:mm:ss.000" Application.Wait Now() + TimeSerial(0, 0, 1) ws.Range("a2").formula = "=now()" ws.Range("a2").numberFormat = "dd/mm/yyyy h:mm:ss.000" ws.Range("a3").formula = "=a2-a1" ws.Range("a3").numberFormat = "h:mm:ss.000" var diff as double diff = ws.Range("a3") 

除了AdamRalph( GetTickCount() )所描述的方法之外,你可以这样做:

  • 使用QueryPerformanceCounter()QueryPerformanceFrequency() API函数
    你如何testingVBA代码的运行时间?
  • 或者,对于没有访问Win32 API的环境(比如VBScript),这个:
    http://ccrp.mvps.org/ (查看“高性能计时器”的可安装COM对象的下载部分,它们是免费的。)