【问题标题】:Excel VBA Ontime function with Milliseconds [duplicate]毫秒的Excel VBA Ontime函数[重复]
【发布时间】:2021-05-01 12:50:11
【问题描述】:
我编写了这段代码,使用 ontime 函数每秒运行一个过程:
Sub startTimer()
Application.OnTime (Now + TimeValue("00:00:01")), "increment"
End Sub
Sub increment()
'some code here
startTimer
End Sub
代码运行良好,但有什么方法可以增加几分之一秒(例如:10 毫秒)
?
【问题讨论】:
-
-
OnTime 时间表的分辨率为 1s,最小为 1s。因此,OnTime 无法满足您的要求。您可以通过一些 API 调用来实现它。 See here
标签:
excel
vba
milliseconds
【解决方案1】:
试试这个:
Sub startTimer()
Const MILLISECOND_MULTIPLIER As Double = 0.000000011574;
' bracket is optional, but kept for clarity
Application.OnTime (Now + (MILLISECOND_MULTIPLIER * 10)), "increment")
End Sub
这是受到现有答案 here 的评论的启发。
【解决方案2】:
如果认真使用毫秒,确实在减法或比较值时,请务必使用 Decimal 而不是 Double 进行计算以避免位错误:
Dim OneMillisecond As Variant
OneMillisecond = CDec(TimeSerial(0, 0, 1) / 1000)
' OneMillisecond = 0.0000000115740740740741
TenMilliseconds = OneMillisecond * CDec(10)
MS Access Can Handle Millisecond Time Values - Really