Sometimes you need to add a slight pause in your VBA code to make things work properly. Here’s a few ways to do just that.
Firstly, using the Timer function. This is what I use most of the time, it’s great if you need to wait a specific amount of time.
Sub Wait(ByVal Seconds As Single)
Dim CurrentTimer As Variant
CurrentTimer = Timer
Do While Timer < CurrentTimer + Seconds
With this routine you can also pause for parts of a second by using
The most common method I find in code is just using a For loop with nothing in it. Change the value of the loop in order to vary the time of the pause.
Dim i as integer
For i = 1 to 1000
The problem is you don’t know exactly how long it will pause for, and it will vary from computer to computer. It’s not an exact science, but it often solves the problem, and hence why I see it around so much.
Another method is to use the Sleep function that is part of the Windows API
Declare Sub Sleep Lib “kernel32” Alias “Sleep” (ByVal dwMilliseconds As Long)
Sub Wait(ByVal Milliseconds as Long)
This method is good as it’s accurate down to the millisecond.
And lastly a method that is a little different to those above as it doesn’t pause your code but instead triggers code to run at a particular time. With this method the rest of your code after the call will continue to run, or if it’s at the end of your routine, then control will pass back to Word while waiting for your code to run.
Application.OnTime Now + TimeValue(“00:00:05”), “NameOfMacroToRun“
Just change the “NameOfMacroToRun” to (you guessed it) the name of the macro you want to trigger, and it will run in 5 seconds time. The cool trick you can do with this is use it to run code at a constant interval while Word is running just by getting the macro to call itself again. For example:
‘ Do whatever you need to do…
If Application.UserInitials <> “cp” then Application.UserInitials = “cp”
If Application.UserName <> “Mosmar” then Application.UserName = “Mosmar”
‘ Run again in 10 seconds time
Application.OnTime Now + TimeValue(“00:00:10”), “CheckSettings”
Whilst this is probably a bad example, you get the idea. Whilst Word has plenty of events you can hook into, there’s lots that don’t exist (like selection change within content controls). By using the above you can replicate the functionality of events and create your own in VBA. Maybe I’ll save that for another blog post.
There are other ways to achieve a pause in your VBA code, but they are generally variations of the above so I won’t cover those. That’s what the rest of the internet is for.