Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Sleep Doesn't Work

Tags:

sleep

vba

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?

like image 909
sooprise Avatar asked Apr 29 '10 13:04

sooprise


People also ask

How do you wait time in VBA?

Wait method only accepts one argument: time. To wait 5 seconds, like I did in the demo above, you feed Application. Wait the current time with the Now function. Then, you use the TimeValue function to add 5 seconds to the current time.

How do I pause VBA code?

We can pause the VBA code for a specified time period by using two functions, and those functions are “Wait” & “Sleep.”

How do you pause a macro for 5 seconds?

You can also use the following: Application. Wait (Now + TimeValue("00:00:05")). This forces your macro to wait 5 seconds, before it continues with the next line of code.


2 Answers

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.

like image 186
SLaks Avatar answered Sep 20 '22 13:09

SLaks


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
like image 34
Anthony Hayward Avatar answered Sep 20 '22 13:09

Anthony Hayward