如何在excel vba中给出不到一秒的时间延迟?

Rit*_*ito 30 excel vba excel-vba

我想在一段不到1秒的时间后重复一个事件.我尝试使用以下代码

Application.wait Now + TimeValue ("00:00:01")
Run Code Online (Sandbox Code Playgroud)

但这里最小延迟时间是一秒钟.如何延迟说半个月?

Dou*_*ncy 23

您可以使用API​​调用和睡眠:

把它放在你的模块的顶部:

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Run Code Online (Sandbox Code Playgroud)

然后你可以在这样的过程中调用它:

Sub test()
Dim i As Long

For i = 1 To 10
    Debug.Print Now()
    Sleep 500    'wait 0.5 seconds
Next i
End Sub
Run Code Online (Sandbox Code Playgroud)

  • 如果代码是64位操作系统,则需要使用`PtrSafe`,请参阅https://support.microsoft.com/en-us/kb/983043 (4认同)

小智 16

我发现这个在另一个网站上不确定它是否有效.

Application.Wait Now + 1/(24*60*60.0*2)
Run Code Online (Sandbox Code Playgroud)

数值1 = 1天

1/24是一小时

1 /(24*60)是一分钟

所以1 /(24*60*60*2)是1/2秒

您需要在某处使用小数点来强制浮点数

资源

不确定这是否值得一试几毫秒

Application.Wait (Now + 0.000001) 
Run Code Online (Sandbox Code Playgroud)

  • 你的半秒示例是正确的,但毫秒示例不是.一天的1毫秒= 1 /(1000*24*60*60),一天为0.000000011574.将代码中的毫秒作为常量:`Const ms As Double = 0.000000011574`例如,等待四分之一秒,`Application.Wait Now + ms*250` (12认同)

小智 13

呼叫waitfor(.005)

Sub WaitFor(NumOfSeconds As Single)
    Dim SngSec as Single
    SngSec=Timer + NumOfSeconds

    Do while timer < sngsec
        DoEvents
   Loop
End sub
Run Code Online (Sandbox Code Playgroud)

VBA中的定时延迟


Jon*_*ier 6

每个人都尝试过Application.Wait,但这并不可靠。如果您要求它等待不到一秒,您将得到 0 到 1 之间的任何值,但接近 10 秒。这是使用 0.5 秒等待的演示:

Sub TestWait()
  Dim i As Long
  For i = 1 To 5
    Dim t As Double
    t = Timer
    Application.Wait Now + TimeValue("0:00:00") / 2
    Debug.Print Timer - t
  Next
End Sub
Run Code Online (Sandbox Code Playgroud)

这是输出,平均为 0.0015625 秒:

0
0
0
0.0078125
0
Run Code Online (Sandbox Code Playgroud)

诚然,计时器可能不是测量这些事件的理想方式,但您明白了。

计时器方法更好:

Sub TestTimer()
  Dim i As Long
  For i = 1 To 5
    Dim t As Double
    t = Timer
    Do Until Timer - t >= 0.5
      DoEvents
    Loop
    Debug.Print Timer - t
  Next
End Sub
Run Code Online (Sandbox Code Playgroud)

结果平均值非常接近 0.5 秒:

0.5
0.5
0.5
0.5
0.5
Run Code Online (Sandbox Code Playgroud)


小智 5

我已经尝试过了,它对我有用:

Private Sub DelayMs(ms As Long)
    Debug.Print TimeValue(Now)
    Application.Wait (Now + (ms * 0.00000001))
    Debug.Print TimeValue(Now)
End Sub

Private Sub test()
    Call DelayMs (2000)  'test code with delay of 2 seconds, see debug window
End Sub
Run Code Online (Sandbox Code Playgroud)