Declaring & Calling The Sleep API

spcurtis81 picture spcurtis81 · Mar 11, 2014 · Viewed 15k times · Source

I have read many threads on implementing the Sleep API however most are a step ahead of where I am at in terms of knowledge to some guidance would be greatly appreciated.

I have a macro in VBA which I would like to add pauses to, between steps (purely aesthetic rather than functional) however I am struggling with the basic declaring and calling.

I understand that first I must declare the api and that the code for this is...

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

however, I am confused with regards to where this should go. Should it go in a module of it's own or can it be stated at the top of the macro module?

Then to call the function do I simply add a line to the macro of...

Call Sleep (1000)

I'd appreciate it if anyone can help with this question and appreciate your patience with my basic grasp.

Answer

user2140173 picture user2140173 · Mar 11, 2014

The declaration of Sleep should go to the top of a module. Standard coding module.

You can omit Call and just use

Sleep 1000  ' 1 second delay

anywhere within an existing sub, so

Option Explicit

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

Sub Main()

    ' wait 3 seconds
    Sleep 3000

End Sub

enter image description here


an alternative without declaring the Sleep sub would be

Application.Wait Now + TimeValue("00:00:03") ' waits 3 seconds