VBA – How-to Pause, Delay, Wait or Sleep Your Code

Blue Round Pause Button

Ever needed to temporarily pause or slowdown the execution of your code?

These are rare situations, but they do occur. Below are a couple possible techniques to pause/delay/slowdown your code.

Using the Sleep API

#If VBA7 Then
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#Else
    Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If

Then you can simply use it by doing something along the lines of:

Sleep (1000) 'Wait for 1 second

Using Application.Wait

This technique only works in Microsoft Excel however.

Function Wait(lngSeconds As Long)
    'lngSeconds - Number of seconds to delay your code by
    Application.Wait DateAdd("s", lngSeconds, Now)
End Function

Then you can simply use it by doing something like:

Wait(1) 'Wait for 1 second

Such code can be useful to allow external programs to load, finish execution, web pages to load, …

Other Resources on the Subject