VBA 睡眠不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2737706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:25:00  来源:igfitidea点击:

VBA Sleep Doesn't Work

vbasleep

提问by sooprise

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?

我知道我在这里做错了。我正在尝试使用 sleep 函数来延迟我的代码,但我收到“Sub or Function not defined”错误。有小费吗?

回答by SLaks

VBA does not have a Sleepfunction.

VBA 没有Sleep函数。

You can import it from Kernel32.dll like this:

您可以像这样从 Kernel32.dll 导入它:

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

Note that this will freeze the application.
You can also call DoEventsin a Whileloop, which won't freeze the application.

请注意,这将冻结应用程序。
您还可以DoEventsWhile循环中调用,这不会冻结应用程序。

回答by Anthony Hayward

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

我尝试过的一切似乎都会挂起应用程序,包括 Application.Wait。不过,这似乎有效:

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

While Now() < waitTill
    DoEvents
Wend

回答by Alex K.

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

您还可以暂停当前的宏上下文,Application.Wait T这不会阻止整个过程。

回答by Babu

Application.Wait DateAdd("m", 10, Now) ' Wait for 10 Minutes
 Application.Wait DateAdd("s", 10, Now) ' wait for 10 seconds

回答by Gajendra Santosh

Pausing an application for 10 seconds.

暂停应用程序 10 秒钟。

Application.Wait (Now + TimeValue("0:00:10"))

回答by Riccardo La Marca

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

使用此代码 Excel 不会冻结并且 CPU 使用率很低:

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