Is there a way to use VBA (excel) to generate a clock time with accuracy to a tenth of a second or less?
eg:
Sub test()
MsgBox Format(Time, \"hh:
You can use the Windows API to get a more accurate time (including milliseconds) as follows.
Private Type SYSTEMTIME
Year As Integer
Month As Integer
DayOfWeek As Integer
Day As Integer
Hour As Integer
Minute As Integer
Second As Integer
Milliseconds As Integer
End Type
Public Declare Sub GetSystemTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)
Public Function GetMilliseconds()
'' This function returns an accurate version of the milliseconds elememt of the current date/time
Dim tSystem As SYSTEMTIME
GetSystemTime tSystem
GetMilliseconds = tSystem.Milliseconds
End Function
Credit goes to http://custom-designed-databases.com/wordpress/2011/get-milliseconds-or-seconds-from-system-time-with-vba/ where there is also more detailed information on getting the milliseconds from the system time in VBA.
The following VBA code returns the current local time as a String, including milliseconds. If you need system time, simply replace GetLocalTime by GetSystemTime.
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" (ByRef lpLocalTime As SYSTEMTIME)
Public Function NowMilli() As String
Dim tTime As SYSTEMTIME
Dim sTwo As String, sThree As String
Dim sOut As String
sOut = "yyyy-mm-dd hh:mm:ss.mmm"
sTwo = "00": sThree = "000"
Call GetLocalTime(tTime)
Mid(sOut, 1, 4) = tTime.wYear
Mid(sOut, 6, 2) = Format(tTime.wMonth, sTwo)
Mid(sOut, 9, 2) = Format(tTime.wDay, sTwo)
Mid(sOut, 12, 2) = Format(tTime.wHour, sTwo)
Mid(sOut, 15, 2) = Format(tTime.wMinute, sTwo)
Mid(sOut, 18, 2) = Format(tTime.wSecond, sTwo)
Mid(sOut, 21, 3) = Format(tTime.wMilliseconds, sThree)
NowMilli = sOut
End Function
I have noticed through some trial and error that current time is shown atleast upto 10 milliseconds if you assign a formula to a cell opposed to using the function directly in vba. I generally use the NOW() function for current time.
If my code is as follows:
sub test()
cells(1,1)=now()
end sub
then cell A1 shows time upto seconds, not milliseconds (time would be shown as 10:38:25.000)
if I use this code:
sub test()
cells(2,1).formula "=now()"
cells(1,1)=cells(2,1)
end sub
Then time is shown upto milliseconds in A1 (time would be shown as 10:38:25.851)
I think that Time
doesn't give that information.
You can use Timer
for extra accuracy.
In Microsoft Windows the Timer function returns fractional portions of a second. On the Macintosh, timer resolution is one second.
Here is an example:
MsgBox Format(Time, "hh:mm:ss:" & Right(Format(Timer, "#0.00"), 2))
Here is a much simpler way:
t = Evaluate("Now()")
This evaluates the current time as a worksheet function in milliseconds, rather than as a VBA function in seconds.