Vba excel delay что это

Return to VBA Code Examples

In this Article

  • Use of Application.Wait Method
    • Wait 1 Second
    • Wait Until
  • Use of Sleep Method
  • Using a Loop with Do Events

This tutorial will demonstrate how to pause / delay code using the Wait and Sleep functions in VBA.

When we create large VBA programs that perform a lot of calculations, or perhaps even call external program to run, we may require our VBA code to stop running for a specific length of time while the external process is taking place.   VBA has a few methods available in order to achieve this.

Use of Application.Wait Method

If we need to pause our macro’s running for some time or until a specified time has been reached before executing the next step, we can use the Application.Wait method.  This could be useful, for example, if we have automated a login process to a website and need to wait some seconds until the page is loaded before our macro continues running.

Wait 1 Second

Including this line below into your macro, its running will be paused for approximately 1 second:

Application.Wait (Now + TimeValue("0:00:01"))

Wait Until

In some cases you will need to wait until a specific time. With this line below your macro will not proceed before 9am:

Application.Wait "09:00:00"

Please note that the Application.Wait does not accept delays of less than 1 second.

Use of Sleep Method

If you need a more precise way of pausing your macro, you can use the Sleep method.

Sleep is a Windows API function, that is, it is not part of VBA. It can be accessed by using a special declaration statement.

If you are using the 64-bit version of Microsoft Office, you can insert the following statement into a new module or at the beginning of the module (not directly in the subroutine) you want to use the Sleep function in:

Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr)

With 32-bit version use this line:

Public Declare Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr)

After declaring the Sleep function, you have access to it in you subroutines like this:

Sleep 10000

With this line above your macro will be paused for 10,000 milliseconds, i.e., 10 seconds.

Using a Loop with Do Events

The big disadvantage of using the Wait and Sleep methods is that the user cannot do anything in Excel while waiting for the macro to continue.  A user could think that Excel has stopped responding and while the user can then use Ctl+Break to interrupt the macro, this defeats the purpose of putting a pause in the macro to begin with.

To overcome this problem, we can use a loop with a method called DoEvents.

Public Sub Test()
    Dim i As Long
    For i = 1 To 20000
        Range(“A1”).Value = i
        DoEvents
    Next i
End Sub

Now, while Excel is running the macro above, the user can continue to interact with Excel – we can change tabs or format cells for example – basically, the macro is continuing to run but the Excel screen is not frozen.   We could use a similar loop to create a timer function in Excel and incorporate the DoEvents method in that to unfreeze the screen while the timer is running.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Home / VBA / VBA Wait and Sleep Commands to Pause and Delay

VBA Wait Command

In VBA, the WAIT command (method) helps you to put a wait on all the activities that you do in Excel for a particular time or up to a specific time. In simple words, you can make VBA wait for a few seconds, minutes, or even hours, or up to fix time. It has one argument that needs you to specify.

Steps to use VBA Wait

  1. First, use the keyword “Application” and type a dot (.) to get the list of properties and methods.
  2. After that, select or type the “Wait” method.
  3. Now, specify the “Time” argument to tell VBA that how much time you want to wait.
  4. In the end, run the code to put wait for all the activities in Excel.

In this code, you have used the NOW and TIMEVALUE (VBA Functions) to tell VBA to wait for ten seconds starting from the moment you run the code. So once the ten seconds passed the IF statement will test the condition and run showing you a message box with the message “Wait Over”.

Sub vba_wait_example()

If Application.Wait(Now + TimeValue("00:00:10")) = True Then
    MsgBox "Wait Over"
End If

End Sub

You can also use the Wait method to let Excel wait for all the activities up to a specific time. The following code waits until 01:00 PM. So, as it’s 12:52 in my system right now this code of line will make it wait for the next 8 minutes.

Application.Wait "13:00:00"

Note: With the wait method, you can only make wait a second not less than that.

Sleep is a windows function (under windows DLL files; you need to import this function using a code statement) that can help you pause or add a delay while running a macro. In this function, you can specify the time in milliseconds, but you can’t stop the sleep function once it’s put everything on pause.

Use Sleep Function in VBA

  1. First, you need to use the code statement to import the sleep function from the “kernel32 library”.
  2. And then you need to make sure to append the “PtrSafe” statement if you are using 64 Bit Excel.
  3. Next, you need to call the sleep function in the code.
  4. In the end, specify the time (milliseconds) for which you want to delay the code.
If VBA7 Then
'For 64-Bit versions of Excel 
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
Else
'For 32-Bit versions of Excel
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
End If

 Sub vba_sleep()
     Sleep (10000)
     'add code here
     MsgBox "Finished"
 End Sub

In the above code, you have 10000 milliseconds, which equals 10 seconds. When you run this code, it will delay the code for 10 seconds and then show a message box.

Note: When you use the sleep function, it stops everything in Excel for the time you have defined, you can’t even break it. Make sure to check out this link from Microsoft on Compatibility Between the 32-bit and 64-bit Versions

There’s More

VBA With Statement | VBA Status Bar | VBA ScreenUpdating | VBA Random Number | Line Break in a VBA Code | VBA Immediate Window (Debug.Print) | VBA Concatenate | VBA Module | VBA Random Number

You may want some way of pausing or delaying VBA code execution and you can do this with two functions called Wait and Sleep. You can also do this using a loop, and we will look at that approach too, but first we’ll look at the functions available to Excel.

Why would you pause the code? Maybe you need to wait for another task to finish, for instance if you made a call to a Windows API/shell function. Or you may want to wait for the user to update data in the sheet, or you just want to run a macro at a set time.

Download the Workbook With Sample VBA Code

The queries in this Excel file can be copied/pasted into the Power BI Desktop Advanced Editor and will work there too.

Enter your email address below to download the workbook with the data and code from this post.

By submitting your email address you agree that we can email you our Excel newsletter.

Application.Wait

The .Wait method is available within Excel as a VBA function, as opposed to Sleep (see below). You can use it to specify that a macro is paused for a specific period of time.

This example makes the macro pause for approximately 10 seconds:

Application.Wait (Now + TimeValue("0:00:10"))

Or you can pause execution until a specific time e.g. this will pause a macro until 11am:

Application.Wait "11:00:00"

Wait does not accept delays of less than 1 second.

Sleep is a Windows API function, that is, it is not part of VBA it is part of the Windows operating system. But we can access it by using a special declaration statement in our VBA.

This declaration statement serves two purposes. Firstly, it tells Excel where to find the function, secondly it allows us to use the 32bit version of the function in 32bit Excel, and the 64bit version of the function in 64bit Excel.

The Declare statement looks like this

#If VBA7 Then ' Excel 2010 or later

    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr)

#Else ' Excel 2007 or earlier

    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As Long)

#End If

Note : I’ve tested this code in Excel 2010 and 2013 only.

You can read more about these type of Declare statements and 32bit/64bit Office on Microsoft’s MSDN site

Sleep allows us to pause a macro for X milliseconds, which is a better resolution than Wait which has a minimum delay of 1 second. So to pause a macro for 5 seconds using Sleep we write this

Sleep 5000

Loops

The big drawback of using Wait or Sleep, is that Excel locks you out until the wait/sleep period has finished. You can use CTRL+BREAK to interrupt the macro, but Excel won’t accept input from the keyboard or mouse whilst paused using Wait or Sleep.

Events are suspended and anything you have scheduled using Application.OnTime is also delayed until the pause has finished. If you didn’t know what was happening, it looks like Excel has hung whilst Sleep or Wait are in effect. Background processes like printing and recalculation do carry on though.

To overcome this drawback you can use a loop to pause VBA execution, and also allow other things to happen whilst waiting. Macro execution isn’t actually paused, it’s just not doing anything other than running some loop commands.

A loop has an added advantage as Mac users can use them, whereas Wait and Sleep are not available on a Mac.

A simple loop would look something like this

Sub WasteTime(Finish As Long)

    Dim NowTick As Long
    Dim EndTick As Long

    EndTick = GetTickCount + (Finish * 1000)
    
    Do

        NowTick = GetTickCount
        DoEvents

    Loop Until NowTick >= EndTick

End Sub

We write a sub called WasteTime, which when called from another sub or function has a value passed into it which is the number of seconds that we want it to do nothing, like so:

WasteTime(10)

The key here is the DoEvents method. DoEvents tells Excel to check if there is anything else the system wants to do like accept input from the keyboard or mouse. In this example, my macro is executing but allows the user to type into the worksheet. After approximately 10 seconds a message is then displayed.

The GetTickCount function is another Windows API function that we access by using another Declare statement. It returns the number of milliseconds since the computer started up.

The parameter, Finish that we pass into the WasteTime sub, is the number of seconds we want to delay code execution. To convert this to milliseconds, we multiply Finish by 1000.

Timer Resolution

In my examples I have used the word approximately when describing the delays I’m trying to achieve. I say approximately because the actual duration of the pause in the execution of the code depends on the resolution of the timer on your computer.

I could give you a very complicated description why this is so, or you could Google it, but let’s just say, if you want to delay something by 10s, then you will delay it for around 10s. It’ll only be out by a few milliseconds, which is perfectly fine for the type of things I am doing. I just wouldn’t use it to time Usain Bolt.

Disclaimer – Please test the code yourself, it may not work in your environment. All code provided as is without any warranty

Wait and Sleep functionality in programs is required to hold or pause the program execution for a specified time. These methods suspend all the activities of Microsoft Excel and sometimes may also prevent you from performing other operations on it until the pause is in effect.

However, your computer can simultaneously process other background tasks like printing or thread ordering.
WAIT & SLEEP Functions IN VBA

Significance of Wait and Sleep Functions in VBA:

These functions can be quite useful when you need to hold the program to wait for some other process or task (not directly connected or communicable to the VBA engine) that is yet to be completed.

In such cases, you can find out the maximum time required for completing such a task, and then in your code, you hold the execution for that amount of time.

For example, We have a VBA code that can run some other executable (.exe) and after running that executable you need to wait for that executable to complete and then continue the code. So, in such a case we know that VBA cannot directly communicate with the executable file.

Hence we can code in such a way that first, we start that executable then let the code wait for 10 seconds (max time required for this executable to run), and then continue the execution again.

VBA Wait Function in Excel:

The WAIT is a VBA function only available in Excel. Its syntax is as follows:

Here ‘Time’ specifies the time at which you want the macro to resume again. ‘Time’ should always be in Microsoft excel time format.

Let’s see some examples of Wait Function in VBA:

Example 1: Pausing a code till 2.00 PM today.

Sub WaitTest()
MsgBox ("This application is started!")
Application.Wait "14:00:00"
MsgBox ("Excecution resumed after 2PM")
End Sub

Example 2: Pausing an application for 10 seconds.

Sub WaitTest()
MsgBox ("This application is started!")
Application.Wait (Now + TimeValue("0:00:10"))
MsgBox ("Excecution resumed after 10 Seconds")
End Sub

Example 3: Using the VBA Wait function to create a program that tells time after every minute (till 10 loops).

Public Sub TalkingTime()
For i = 0 To 10
Application.Wait (Now + TimeValue("0:01:00"))
Application.Speech.Speak ("The Time is" & Time)
Next i
End Sub

Now let’s move to Sleep Function.

Sleep Function:

Sleep is a windows function and not a VBA Function, but you can still use this function in VBA code by calling the windows Sleep API. Actually sleep is a function present inside Windows DLL files. So, before using them you have to declare the name of API above the code in your module.

The syntax of the Sleep statement is as follows:

Here, ‘delay’ specifies the time in milliseconds till which you have to pause the execution.

Let’s see some examples of Sleep Function in VBA:

Example 1: Pausing an application for 10 seconds

#If VBA7 Then
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64 Bit Systems
#Else
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds as Long) 'For 32 Bit Systems
#End If
Sub SleepTest()
MsgBox "Execution is started"
Sleep 10000 'delay in milliseconds
MsgBox "Execution Resumed"
End Sub

Example 2: Halting the code for a user-defined delay by using an InputBox function.

Sub SleepTest()
On Error GoTo InvalidRes
Dim i As Integer
i = InputBox("Enter the Seconds for which you need to pause the code :")
Sleep i * 1000 'delay in milliseconds
MsgBox ("Code halted for " & i & " seconds.")
Exit Sub
InvalidRes:
MsgBox "Invalid value"
End Sub

Difference between VBA Wait and Sleep Function:

The job of both of these functions is the same but the sleep function is not as accurate as Wait. Sleep statement depends on the processor’s ticks to calculate the time delays which may vary slightly on different machines. But this is not the case with Wait Function.

The advantage of the Sleep statement over Wait is that it is quite flexible as you can give the time delays in milliseconds. While in the Wait function you can only delay the application by whole seconds.

So, this was all about VBA Wait and Sleep Functions. Do let us know in case you have any queries related to the topic.

Idle time is often wasted time, however, sometimes you just need to wait for certain events to happen before you can continue code execution. VBA extends a couple of approaches to managing your idle time – the most popular approach is the Sleep procedure. The VBA Sleep procedure pauses code execution for a certain amount of time putting the whole processes in a type of coma. It is one of the most popular approaches to pausing code execution, and at the same time simplest one. As I will try to prove – there are better, more productive approaches to pausing your code execution or utilizing potentially application idle time.

'Sleep for 1 second
Call Sleep(1000) 

'Wait for 1 second
Call Application.Wait( DateAdd("s", 1, Now) )

What is the difference between both? And when to use the VBA Sleep function as opposed to the Application Wait VBA function?

VBA Sleep function

Let us start by introducing the VBA Sleep function. The Sleep function pauses the entire process for a certain delay specified in milliseconds. The drawback of using VBA Sleep is that it freezes Excel until the delay is done. This means that you cannot continue working on your spreadsheet and that Sleep is not to be used for long durations of time as in some extreme cases might cause Excel to assume the application has crashed.

Definition and Syntax

The Sleep function is not available by default in VBA, and has to be imported from the kernel32 library. For 64 Bit procedures we need to make sure to append the PtrSafe statement.

#If VBA7 Then  
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal milliseconds As LongPtr) 'MS Office 64 Bit
#Else  
    Public Declare Sub Sleep Lib "kernel32" (ByVal milliseconds as Long) 'MS Office 32 Bit
#End If  

Parameters

Parameter Variable Type Description
milliseconds Long The amount of milliseconds the process should be paused for

VBA Sleep example

The Sleep function is pretty straightforward to use:

Sleep 1000 'Sleep for 1000 milliseconds = 1 sec

Other VBA Sleep examples

'Sleep for 10 seconds
Sleep 10000
'Sleep for 1 minute
Sleep 60000 '60 * 1000
'Sleep for 1 hour
Sleep 3600000 '3600 * 1000

Pros and Cons

The pros of using the Sleep function:

  • Easy to use
  • Precise sleep intervals (in milliseconds)

The cons of using the Sleep function:

  • Requires importing Sleep function
  • Freezes the entire process i.e. Excel does not respond
  • There is no way to stop the Sleep function

The problem with the Sleep function is that it freezes your process entirely – preventing any input or interaction with your application (even breaking code execution). Why not use that time more productively? Or let the user cancel code execution?

VBA Application.Wait function

The VBA Application.Wait is a native VBA function that pauses code execution until a certain time is reached. As opposed to VBA Sleep, the Application Wait procedure does not freeze Excel during the pause. This means you can keep working on your Excel Workbook during the delay. Do remember, however, that during macro execution no changes can be undone (CTRL+Z will not undo changes made during macro running). What is more Application Wait does not allow you to wait for periods shorter than a single second.

Syntax

The syntax of the VBA Application.Wait function is:

Application.Wait( time )

Parameters

Parameter Variable Type Description
time Variant The time when the function should return e.g. 15:30:00 for 3:30 pm.

VBA Application.Wait example

The Application.Wait function is similarly pretty easy to use, although a little different than what you might expect with the Sleep function. This is because Application.Wait will wait until a time is reached instead of waiting for a precise interval of time.

Application.Wait "15:30:00"

This approach is of course less practical as usually you want to wait simply for a precise interval of time, like say 3 seconds. That is why we need to aid ourselves with the use of either the DateAdd function or the TimeValue function:

Application.Wait DateAdd("s", 1, Now) 'Wait for 1 second
'same as
Application.Wait Now + TimeValue("0:00:01) 'Wait for 1 second

What does the function above do? It adds 1 second to the current clock time and asks VBA to wait until that moment to return from the function. You can similarly wait for longer periods of time.

Other VBA Wait examples

'Wait for 10 seconds
Application.Wait DateAdd("s", 10, Now)
'Wait for 1 minute
Application.Wait DateAdd("n", 1, Now)
'Wait for 1 hour
Application.Wait DateAdd("h", 1, Now)
'Wait for 1 minute 30 seconds
Application.Wait DateAdd("s", 90, Now) '00:01:30 = 60 + 30
'Wait for 1 hour 2 minutes and 30 seconds
Application.Wait DateAdd("s", 3750, Now) '01:02:30 = 3600 + 120 + 30

Pros and Cons

The pros of using the Application.Wait function:

  • Fairly easy to use (a little less obvious than Sleep)
  • You can break the function at any time (does not freeze the entire process)
  • Available natively from VBA

The cons of using the Application.Wait function:

  • Allows you to wait for intervals shorter no shorter than 1 second

The Application.Wait function is a little less obvious to use, but won’t freeze your VBA Project allowing you to hit Esc at any time and resume control over your project.

VBA DoEvents

If you thought those were your only options – you were wrong. VBA thankfully allows you to also use another function called DoEvents. The function seemingly….does nothing. Seriously, it doesn’t do anything more that handle all MS Office events. Now why would we want to use the DoEvents function you might ask? Well, remember that Application.Wait does not allow you to wait for intervals shorter than 1 second? On the other hand Sleep freezes your application entirely although being more granular.

Want an example of the VBA DoEvents function?

DoEvents 'That's it!

DoEvents is especially useful when you have a lot of computations going on but want to keep your VBA Project responsive WITHOUT introducing significant (1 second) delays.

VBA DoEvents example

Usually when running a macro you will want to turn off ScreenUpdating focusing your macro only on your computations. This however may seem to your user like the application has frozen. DoEvents is to be used in pair with the ScreenUpdating property:

Application.ScreenUpdating = False 'Turn off screen updating
'...code here...
DoEvents 'Refresh the screen "on demand"
'...code here...

Usually you might want to use it like this:

Application.ScreenUpdating = False 'Turn off screen updating
'...code here...
Do Until someThingHappened = True
  'I am waiting for something to happen
  DoEvents
Loop
'...code here...

Conclusions

Let’s summarize our findings:

Use Application.Wait for > 1 second intervals. Application.Wait can be used well to pause code execution without freezing the application as long as you need to pause for more that 1 second (integer values).

Use DoEvents to refresh the screen on demand. Don’t want your user to get restless? Want to pause for a minimal interval just to refresh your application screen? Don’t bother with Sleep and use DoEvents instead!

Use Sleep for precise intervals. Need to wait for 500 milliseconds – no more no less? Ok… seems like you are stuck with the Sleep function.

Like this post? Please share to your friends:
  • Vba excel date функция
  • Vba excel currentregion rows count
  • Vba excel createobject wscript shell run
  • Vba excel countifs примеры
  • Vba excel countif пример