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?
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.
We can pause the VBA code for a specified time period by using two functions, and those functions are “Wait” & “Sleep.”
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With