Excel vba задержка выполнения макроса

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!

 

Borodets

Пользователь

Сообщений: 220
Регистрация: 01.01.1970

Добрый день подскажите в приведенном ниже коде производиться обновление вебзапроса, после обновления  эти данные должны скопироваться в другое место, подскажите как прописать задержку чтоб вебзапросы обновились, а потом уже производилось копирование иначе копируються старые данные (еще не обновленные)  

  Sub погода()  
‘ Макрос записан 10.09.2010 (Шишкин П.Е.)  
   ActiveWorkbook.RefreshAll  
   Sheets(«Погпл 2»).Select  
   Application.Run «‘ГТП Моргудонская.xls’!delstolb»  
   Sheets(«Погода план «).Select  
   Application.Run «‘ГТП Моргудонская.xls’!delstolb»  
   pgdcopi  
End Sub  
Private Sub pgdcopi()  
ion  
Application.Wait Now + TimeSerial(0, 0, 50) ‘ Вот гдето здесь нужно приостановить  
   Dim foundCell As Range, iPgd   As Range  
   Dim i As Byte  
   Dim iDatei As String  
   Sheets(«Детка»).Select  
         datarezz = Date — 1  
     Sheets(«Погода «).Select  
Set r = ThisWorkbook.Worksheets(«Погода «).Range(«A4000:A50000»)  
Set foundCell = r.Find(datarezz) ‘ LookIn:=xlValues)  
‘MsgBox r  

     If Not foundCell Is Nothing Then  
     ThisWorkbook.Worksheets(«Детка»).Range(«U3:AA26»).Copy  
       ThisWorkbook.Worksheets(«Погода «).Cells(foundCell.Row, 2).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False  
   End If  
   Application.CutCopyMode = False  

         End Sub  
Sub delstolb()  
On Error GoTo Error_del  
   Columns(«O:O»).Select  
   Selection.TextToColumns Destination:=Range(«G1»), DataType:=xlDelimited, _  
       TextQualifier:=xlNone, ConsecutiveDelimiter:=True, Tab:=False, Semicolon _  
       :=False, Comma:=False, Space:=False, Other:=True, OtherChar:=».», _  
       FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True  
Error_del:  
End Sub  
Sub ion()  
   With Application  
       .ScreenUpdating = True ‘обновление экрана  
       .DisplayAlerts = True ‘системные предупреждения  
       .EnableEvents = True ‘контроль событий  
   End With  
End Sub

Оружие не убивает Человека! Человек убивает Человека!!!

Содержание

  1. VBA Wait & Sleep Functions – Pause / Delay VBA Code
  2. Use of Application.Wait Method
  3. Wait 1 Second
  4. Wait Until
  5. Use of Sleep Method
  6. Using a Loop with Do Events
  7. VBA Coding Made Easy
  8. VBA Code Examples Add-in
  9. VBA Wait and Sleep Functions – Explained
  10. Significance of Wait and Sleep Functions in VBA:
  11. VBA Wait Function in Excel:
  12. Example 1: Pausing a code till 2.00 PM today.
  13. Example 2: Pausing an application for 10 seconds.
  14. Example 3: Using the VBA Wait function to create a program that tells time after every minute (till 10 loops).
  15. Sleep Function:
  16. Example 1: Pausing an application for 10 seconds
  17. Example 2: Halting the code for a user-defined delay by using an InputBox function.
  18. Difference between VBA Wait and Sleep Function:
  19. Subscribe and be a part of our 15,000+ member family!
  20. VBA Pause
  21. Pause VBA Code From Running
  22. How to Pause Code using the Wait Method?
  23. How to Pause the VBA Code using the Sleep Method?
  24. Recommended Articles
  25. Функция ожидания VBA
  26. Функция ожидания Excel VBA
  27. Примеры использования функции ожидания Excel VBA
  28. VBA Sleep против VBA Ожидание
  29. Рекомендуемые статьи

VBA Wait & Sleep Functions – Pause / Delay VBA Code

In this Article

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:

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:

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:

With 32-bit version use this line:

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

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.

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 Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

VBA Wait and Sleep Functions – Explained

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.

Table of Contents

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.

Example 2: Pausing an application for 10 seconds.

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

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

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

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.

Subscribe and be a part of our 15,000+ member family!

Now subscribe to Excel Trick and get a free copy of our ebook «200+ Excel Shortcuts» (printable format) to catapult your productivity.

Источник

VBA Pause

Pause VBA Code From Running

VBA Pause one may use to pause the code to execute for a specified amount of time and to pause a code in VBA. We use the application.wait method.

When we build large VBA projects after performing something, we may need to wait for some time to do other tasks. So, how do we pause the macro code to do our task in such scenarios? We can pause the VBA code for a specified period using two functions. Those functions are “Wait” and “Sleep.”

Table of contents

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA Pause (wallstreetmojo.com)

How to Pause Code using the Wait Method?

For example, if executing the code at 13:00:00, if you supply the time as “13:15:00”, it will hold the Macro running for 15 minutes.

We must mention when our code should pause or wait in the time argument.

Code:

Remember, while running this code, my system time is 13:00:00. As soon as we run the code, it will execute the first two lines i.e.

But if you look at the next line, it says Application.Wait (“13:15:00”), so after executing those lines tasks, my Macro will be paused for 15 minutes, i.e., from 13:00:00, it will wait until my system time reaches 13:15:01.

Once my system reaches that time, it will execute the remaining lines of code.

However, this is not the best way of practicing the pause code. For example, let us say you are running the code at different times. Then we need to use the NOW VBA function NOW VBA Function NOW is a date and time function in VBA which is used to get the current system date and time. VBA Now function does not takes any arguments and the return output for this function is date. read more with TIME VALUE function.

Now function returns the current date & time as per the system we are working on.

TIME Value function holds the time from 00:00:00 to 23:59:29.

Assume we need to pause the code for 10 minutes whenever we run the code. Then, we can use the below code.

Code:

It is similar to the previous code, but the only difference is we have added the NOW and TIME VALUE function.

Whenever we run this code, it will hold or pause the execution for 10 minutes.

How to Pause the VBA Code using the Sleep Method?

Sleep is a complicated function in VBA because it is not a built-in function. Since it is not built-in to make it available to use, we need to add the code below to the top of our module.

Code:

You must copy the above code and paste it at the top of the module.

We need to add the above code because SLEEP is a VBA function presented in Windows DLL files, so we need to declare the nomenclature before we start the subprocedure.

Let us look at the example of the SLEEP function now.

Code:

First, we have declared two variables as String.

Then we have assigned the same to show in the message box.

Then, we applied the SLEEP function as Sleep (10000).

Here 10000 is milliseconds, which is equal to 10 seconds in VBA.

Then, we have finally assigned one more TIME function to the variable EndTime.

Now again, we have written a code to show the time.

It will show the difference between start time and end time.

We will now execute the code and see the start time.

When we execute the code, my system time is 13:40:48. Now, my code will sleep for 10 seconds. So, in the end, my time is as follows.

So, like this, we can pause the code from executing it for a specified time.

Recommended Articles

This article is a guide to the VBA Pause Method. Here, we discuss how to pause code from running using the SLEEP and WAIT for function in Excel VBA with examples and a downloadable Excel sheet. You can learn more about VBA from the following articles: –

Источник

Функция ожидания VBA

Функция ожидания Excel VBA

VBA Подождите это встроенная функция для приостановки выполнения кода на указанное время. Это очень похоже на то, что мы делаем в команде Sleep. Чтобы приостановить код, мы используем метод Application.Wait.

Некоторым кодам требуется некоторое время, прежде чем перейти к следующей строке кода из-за выполнения других задач. В этих случаях нам нужно остановить выполнение кода, сделать паузу на некоторое время, а затем продолжить выполнение. Мы можем приостановить выполнение кода двумя способами: методом сна и методом ожидания. В нашей предыдущей статье обсуждалось, что «VBA SleepVBA SleepVBA Sleep — это функция Windows, присутствующая в файлах DLL Windows, которая приостанавливает выполнение программы на определенный период времени (даже в миллисекундах). Подробнее» для приостановки кода VBA. Pause The VBA CodeVBA Пауза помогает приостановить выполнение кода на определенный период. Вы можете приостановить код VBA на определенный период, используя две функции: «Ждать» и «Сон». Подробнее.

Программы для Windows, мобильные приложения, игры — ВСЁ БЕСПЛАТНО, в нашем закрытом телеграмм канале — Подписывайтесь:)

«Подождите», как следует из названия, будет удерживать код макроса, который должен быть выполнен до указанного периода времени. Используя этот метод, нам нужно указать, когда наш код должен приостанавливаться. Далее мы увидим примеры.

Синтаксис функции WAIT следующий.

Нам нужно указать количество времени, на которое наш код должен приостановиться. Как видите, в конце написано Boolean. Это означает, что он возвращает результат в виде логических значений: TRUE или FALSE.

Пока не наступит указанное время, он говорит FALSE. В тот момент, когда наступает указанное время, он возвращает TRUE.

Это не похоже на функцию SLEEP, потому что WAIT — это встроенная функция, где SLEEP — это функция Windows. Итак, прежде чем мы получим доступ к функции SLEEP, нам нужно упомянуть код ниже в верхней части модуля. Но WAIT этого не требует.

Код:

#If VBA7 Then Public Declare Sub Sleep Lib PtrSafe «kernel32» (ByVal dwMilliseconds As LongPtr) ‘Для 64-битных систем #Else Public Declare Sub Sleep Lib «kernel32» (ByVal dwMilliseconds As Long) ‘Для 32-битных систем End If

Примеры использования функции ожидания Excel VBA

Предположим, вы работаете в Excel в полдень в 14:30:00. Вы хотите, чтобы ваш код приостанавливался до тех пор, пока время не станет 14:40:00. Вы можете использовать приведенный ниже код.

Код:

Sub Wait_Example1() Application.Wait «14:40:00» End Sub

Код остановит работу вашего Excel до тех пор, пока время не достигнет 14:40:00 в вашей операционной системе. Предоставление такого времени опасно, потому что мы не всегда работаем с 14:30:00. Он все время меняется.

Скажем, всякий раз, когда вы запускаете код. Вы хотите подождать 2 минуты. Как вы ссылаетесь на это в своем коде?

Итак, мы можем использовать VBA NOWVBA NOWNOW — это функция даты и времени в VBA, которая используется для получения текущей системной даты и времени. Функция VBA Now не принимает никаких аргументов, и возвращаемым результатом для этой функции является функция date.read more с функцией TIME VALUE для ввода указанного времени из текущего времени.

Функция NOW () возвращает текущую дату и время для вашей компьютерной системы. Функция TIMEVALUE представляет время с 00:00:00 до 23:59:59, т.е. 23:59:59 в 24-часовом формате. Он преобразует строковое значение в значение времени.

Например, NOW () + TIMEVALUE (00:02:30) означает текущее время + 2 минуты 30 секунд.

Если текущее время 14:25:30, оно становится 14:28:00.

Вы можете использовать приведенный ниже код, чтобы остановить выполнение вашего кода с текущего времени до следующих 10 минут.

Код:

Sub Wait_Example2() Application.Wait (Now() + TimeValue(«00:10:00»)) End Sub

Важно использовать функцию СЕЙЧАС () для точных пауз. В противном случае есть вероятность, что ваша книга Excel будет приостановлена ​​​​до полуночи. Однако мы можем выйти из метода паузы в любой момент времени, нажав кнопку Esc ключ или Разбить ключ.

Подождите 10 секунд каждый раз, когда цикл запускается

Можно использовать метод ожидания с циклами. Однако бывают ситуации, когда вам может потребоваться подождать 10 секунд каждый раз, когда цикл запускается. Например, посмотрите на данные ниже.

Чтобы рассчитать Прибыль = (Продажи — Стоимость), вы хотите создать цикл, и после каждого цикла вы хотите подождать 10 секунд, чтобы проверить, является ли результат точным или нет. Приведенный ниже код сделает это.

Код:

Sub Wait_Example3() Dim k As Integer For k = 2–9 Cells(k, 4).Value = Cells(k, 2) — Cells(k, 3) Application.Wait (Now() + TimeValue(«00:00) :10»)) Next k End Sub

Этот код будет вычислять столбец прибыли построчно. После завершения первой строки он будет ждать 10 секунд перед вычислением следующей строки.

VBA Sleep против VBA Ожидание

ВБА СОНПОДОЖДИТЕ VBAЭто не встроенная функция VBA. Для доступа к этой функции требуется специальный код. Это встроенная функция VBA, и для доступа к этой функции не требуется никакого специального кода. Для сна требуются миллисекунды в качестве временных рамок. Для ожидания требуются обычные временные рамки. код в миллисекундах. Мы можем задерживать только целые секунды.

Рекомендуемые статьи

Эта статья была руководством по функции ожидания VBA. Здесь мы обсудим, как использовать метод Wait для приостановки выполнения кода с помощью практических примеров и загружаемых листов Excel. Вы можете узнать больше о VBA из следующих статей:

  • Пересечение VBA
  • Разделить функцию в VBA
  • Операторы в VBA

Программы для Windows, мобильные приложения, игры — ВСЁ БЕСПЛАТНО, в нашем закрытом телеграмм канале — Подписывайтесь:)

Источник

Понравилась статья? Поделить с друзьями:
  • Excel vba задать область печати
  • Excel vba задать массив констант
  • Excel vba задать границу ячеек
  • Excel vba добавить модуль
  • Excel vba задание переменной