VBA Sleep Doesn't Work

2019-01-24 03:13发布

I know I'm doing something wrong here. I'm trying to use the sleep function to delay my code, but I get "Sub or Function not defined" error. Any tips?

标签: vba sleep
5条回答
爷、活的狠高调
2楼-- · 2019-01-24 03:42

You can also pause the current macro context with Application.Wait T which won't block the whole process.

查看更多
对你真心纯属浪费
3楼-- · 2019-01-24 03:43
Application.Wait DateAdd("m", 10, Now) ' Wait for 10 Minutes
 Application.Wait DateAdd("s", 10, Now) ' wait for 10 seconds
查看更多
疯言疯语
4楼-- · 2019-01-24 03:52

Everything I've tried seems to hang the application, including Application.Wait. This seems to work though:

waitTill = Now() + TimeValue("00:15:00")

While Now() < waitTill
    DoEvents
Wend
查看更多
Viruses.
5楼-- · 2019-01-24 03:56

VBA does not have a Sleep function.

You can import it from Kernel32.dll like this:

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Note that this will freeze the application.
You can also call DoEvents in a While loop, which won't freeze the application.

查看更多
祖国的老花朵
6楼-- · 2019-01-24 03:56

With this code Excel not freeze and the CPU usage is low:

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sub Delay(s As Single)
    Dim TimeOut As Single
    TimeOut = Timer + s
    Do While Timer < TimeOut
        DoEvents
        Sleep 1 'With this line the CPU usage is 00 instead of 50 with an absolute error of +1ms and the latency of 1ms.
    Loop
End Sub
查看更多
登录 后发表回答