Vba excel дождаться выполнения

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Application.Wait method (Excel)

vbaxl10.chm133242

vbaxl10.chm133242

excel

Excel.Application.Wait

71425d1c-6b37-a510-d8b5-072136e98f04

04/05/2019

high

Application.Wait method (Excel)

Pauses a running macro until a specified time. Returns True if the specified time has arrived.

Syntax

expression.Wait (Time)

expression A variable that represents an Application object.

Parameters

Name Required/Optional Data type Description
Time Required Variant The time at which you want the macro to resume, in Microsoft Excel date format.

Return value

Boolean

Remarks

The Wait method suspends all Microsoft Excel activity and may prevent you from performing other operations on your computer while Wait is in effect. However, background processes such as printing and recalculation continue.

Example

This example pauses a running macro until 6:23 P.M. today.

Application.Wait "18:23:00"

This example pauses a running macro for approximately 10 seconds.

newHour = Hour(Now()) 
newMinute = Minute(Now()) 
newSecond = Second(Now()) + 10 
waitTime = TimeSerial(newHour, newMinute, newSecond) 
Application.Wait waitTime

This example displays a message indicating whether 10 seconds have passed.

If Application.Wait(Now + TimeValue("0:00:10")) Then 
 MsgBox "Time expired" 
End If

[!includeSupport and feedback]

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!

Содержание

  1. Application.Wait method (Excel)
  2. Syntax
  3. Parameters
  4. Return value
  5. Remarks
  6. Example
  7. Support and feedback
  8. Метод Application.Wait (Excel)
  9. Синтаксис
  10. Параметры
  11. Возвращаемое значение
  12. Примечания
  13. Пример
  14. Поддержка и обратная связь
  15. Функция ожидания VBA | Как использовать метод ожидания Excel VBA?
  16. Функция ожидания Excel VBA
  17. Примеры использования функции ожидания Excel VBA
  18. Пример # 1
  19. Пример # 2
  20. Функция ожидания VBA
  21. Функция ожидания Excel VBA
  22. Примеры использования функции ожидания Excel VBA
  23. VBA Sleep против VBA Ожидание
  24. Рекомендуемые статьи
  25. VBA Wait & Sleep Functions – Pause / Delay VBA Code
  26. Use of Application.Wait Method
  27. Wait 1 Second
  28. Wait Until
  29. Use of Sleep Method
  30. Using a Loop with Do Events
  31. VBA Coding Made Easy
  32. VBA Code Examples Add-in

Application.Wait method (Excel)

Pauses a running macro until a specified time. Returns True if the specified time has arrived.

Syntax

expression.Wait (Time)

expression A variable that represents an Application object.

Parameters

Name Required/Optional Data type Description
Time Required Variant The time at which you want the macro to resume, in Microsoft Excel date format.

Return value

Boolean

The Wait method suspends all Microsoft Excel activity and may prevent you from performing other operations on your computer while Wait is in effect. However, background processes such as printing and recalculation continue.

Example

This example pauses a running macro until 6:23 P.M. today.

This example pauses a running macro for approximately 10 seconds.

This example displays a message indicating whether 10 seconds have passed.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Метод Application.Wait (Excel)

Приостанавливает выполняемый макрос до указанного времени. Возвращает значение True, если указанное время наступило.

Синтаксис

выражение.Wait (Time)

выражение: переменная, представляющая объект Application.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Time Обязательно Variant Время, когда нужно возобновить выполнение макроса (в формате даты Microsoft Excel).

Возвращаемое значение

Boolean

Примечания

Метод Wait приостанавливает все действия Microsoft Excel. Пока действует метод Wait может быть запрещено выполнение других действий на компьютере. Однако фоновые процессы, такие как печать и повторные вычисления, продолжаются.

Пример

В этом примере выполняется макрос до 18:23.

В этом примере запущенный макрос приостанавливается примерно на 10 секунд.

В этом примере отображается сообщение, прошли ли 10 секунд.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Функция ожидания VBA | Как использовать метод ожидания Excel VBA?

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

VBA Wait — это встроенная функция, используемая для приостановки выполнения кода на указанное время, она очень похожа на то, что мы делаем в команде сна, а для приостановки кода мы используем метод application.wait.

Некоторым кодам требуется некоторое время, прежде чем перейти к следующей строке кода из-за выполнения других задач. В этих случаях нам нужно остановить выполнение кода и приостановить его на некоторое время, а затем продолжить выполнение. Мы можем приостановить выполнение кода двумя способами: первый — это метод «сна», а второй — метод «ожидания». В нашей предыдущей статье мы обсудили метод «VBA Sleep» для приостановки кода VBA.

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

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

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

Пока не наступило указанное время, он говорит ЛОЖЬ, а в момент наступления указанного времени возвращается ИСТИНА.

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

Код:

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

Пример # 1

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

Код:

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

Допустим, каждый раз, когда вы запускаете код, вы хотите подождать 2 минуты, как это указать в своем коде?

Итак, мы можем использовать функцию VBA NOW с функцией TIME VALUE, чтобы ввести указанное время от текущего времени.

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

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

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

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

Код:

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

Пример # 2

Подождите 10 секунд при каждом запуске цикла

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

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

Код:

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

Источник

Функция ожидания 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, мобильные приложения, игры — ВСЁ БЕСПЛАТНО, в нашем закрытом телеграмм канале — Подписывайтесь:)

Источник

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.

Источник

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

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

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

Оглавление

  • Функция ожидания Excel VBA
    • Примеры использования функции ожидания Excel VBA
      • Пример №1
      • Пример #2
    • VBA Sleep против VBA Ожидание
    • Рекомендуемые статьи

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

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

функция ожидания vba

Нам нужно указать количество времени, на которое наш код должен приостановиться. Как видите, в конце написано 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

.free_excel_div{фон:#d9d9d9;размер шрифта:16px;радиус границы:7px;позиция:относительная;margin:30px;padding:25px 25px 25px 45px}.free_excel_div:before{content:»»;фон:url(центр центр без повтора #207245;ширина:70px;высота:70px;позиция:абсолютная;верх:50%;margin-top:-35px;слева:-35px;граница:5px сплошная #fff;граница-радиус:50%} Вы можете скачать этот шаблон VBA Wait Excel здесь — Шаблон Excel ожидания VBA

Пример №1

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

Код:

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

пример ожидания vba 1.1

Код остановит работу вашего 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

пример ожидания vba 1.2

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

Пример #2

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

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

пример 2.2

Чтобы рассчитать Прибыль = (Продажи — Стоимость), вы хотите создать цикл, и после каждого цикла вы хотите подождать 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

пример 2.1

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

пример 2.3

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

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

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

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

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

I’m running a simple shell command in Excel VBA that runs a batch file in a specified directory like below:

Dim strBatchName As String
strBatchName = "C:folderrunbat.bat"
Shell strBatchName

Sometimes the batch file might take longer on some computer to run, and there are proceeding VBA code that is dependent on the batch file to finish running. I know you can set a wait timer like below:

Application.Wait Now + TimeSerial(0, 0, 5)

But that might not work on some computer that are too slow. Is there a way to systematically tell Excel to proceed with the rest of the VBA code until after the shell has finish running?

Jean-François Corbett's user avatar

asked Apr 11, 2013 at 14:46

user974047's user avatar

2

Use the WScript.Shell instead, because it has a waitOnReturn option:

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "C:folderrunbat.bat", windowStyle, waitOnReturn

(Idea copied from Wait for Shell to finish, then format cells — synchronously execute a command)

Community's user avatar

answered Apr 11, 2013 at 14:52

Nate Hekman's user avatar

Nate HekmanNate Hekman

6,46727 silver badges30 bronze badges

12

Add the following Sub:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
VBA.CreateObject("WScript.Shell").Run Cmd, WindowStyle, True
End Sub

If you add a reference to C:Windowssystem32wshom.ocx you can also use:

Sub SyncShell(ByVal Cmd As String, ByVal WindowStyle As VbAppWinStyle)
Static wsh As New WshShell
wsh.Run Cmd, WindowStyle, True
End Sub

This version should be more efficient.

answered Sep 13, 2015 at 14:59

Anonymous's user avatar

AnonymousAnonymous

1511 silver badge2 bronze badges

Save the bat file on «C:WINDOWSsystem32» and use below code it is working

   Dim wsh As Object
   Set wsh = VBA.CreateObject("WScript.Shell")
   Dim waitOnReturn As Boolean: waitOnReturn = True
   Dim windowStyle As Integer: windowStyle = 1
   Dim errorCode As Integer

   errorCode = wsh.Run("runbat.bat", windowStyle, waitOnReturn)

If errorCode = 0 Then
    'Insert your code here
Else
    MsgBox "Program exited with error code " & errorCode & "."
End If   

answered Oct 9, 2014 at 7:26

Asam's user avatar

AsamAsam

611 silver badge2 bronze badges

This is what I use to have VB wait for process to complete before continuing.
I did not write this and do not take credit.

It was offered in some other open forum and works very well for me:

The following declarations are needed for the RunShell subroutine:

Option Explicit

Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long

Private Declare Function GetExitCodeProcess Lib "kernel32" (ByVal hProcess As Long, lpExitCode As Long) As Long

Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Const PROCESS_QUERY_INFORMATION = &H400

Private Const STATUS_PENDING = &H103&

'then in your subroutine where you need to shell:

RunShell (path and filename or command, as quoted text)

Unheilig's user avatar

Unheilig

16.1k193 gold badges68 silver badges98 bronze badges

answered Mar 5, 2014 at 21:27

geek0's user avatar

geek0geek0

211 bronze badge

1

what you proposed with a change at the parenthesis at the Run command worked fine with VBA for me

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Integer
wsh.Run "C:folderrunbat.bat", windowStyle, waitOnReturn

answered Jul 18, 2014 at 12:20

dadj's user avatar

Either link the shell to an object, have the batch job terminate the shell object (exit) and have the VBA code continue once the shell object = Nothing?

Or have a look at this:
Capture output value from a shell command in VBA?

Community's user avatar

answered Apr 11, 2013 at 14:52

K_B's user avatar

K_BK_B

3,6681 gold badge18 silver badges29 bronze badges

Dim wsh as new wshshell

chdir «Directory of Batch File»

wsh.run «Full Path of Batch File»,vbnormalfocus, true

Done Son

answered May 8, 2014 at 16:05

Borkman's user avatar

1

 

jfd

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

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

#1

06.07.2018 18:23:39

Добрый день,
подскажите, можно ли как-то дождаться завершения процесса копирования файла, а потом продолжить выполнение скрипта. Через паузу по времени к сожалению не гарантированно.Копирование реализовано так

Код
Shell "cmd /c copy """ & updFilePath & updFileArr(i) & """, """ & fnSyn & """"
    Application.Wait Now + TimeSerial(0, 0, 10)

Заранее благодарен

 
 

БМВ

Модератор

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

Excel 2013, 2016

По вопросам из тем форума, личку не читаю.

 

а вызов Shell как функции, случайно не заставляет дождаться окончания работы и получения результата выполнения команды?

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

Ігор Гончаренко, нет. Функция вообще «не знает», вызывают ее как функцию или как подпрограмму (т.е. присваивают чему-то возвращаемое значение или нет).

 

БМВ

Модератор

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

Excel 2013, 2016

Ігор Гончаренко, Игорь, я б сравнил это с WScript.Shell.exec .  только последнее хоть и не ждет, но статусы возвращает и  можно ответ получить, при том ооочень обширный.

По вопросам из тем форума, личку не читаю.

 

jfd

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

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

 

jfd

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

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

#8

07.07.2018 10:49:27

не получилось скопировать файл

Код
Set WshShell = CreateObject("WScript.Shell")
    StatusPrc = WshShell.Run("cmd copy updFilePath & updFileArr(i), fnSyn", 1, True)

CMD запускается, но висит окно пока его не закроешь в ручную, после закрытия отдает статус -1073741510

Что я делаю не так?

 

БМВ

Модератор

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

Excel 2013, 2016

jfd,  Куда /C зажали? Это важно ибо это дает передать COPY как параметр. А так вы запускаете CMD И так как поставили TRUE то пока не завершите его, окно висит. В окончательной версии нет смысла делать окно видимым и 1 замените на 0. Но яб все равно советовал перейти на нормальные для VBA методы. Shell для других вещей пригодится.

По вопросам из тем форума, личку не читаю.

 

jfd

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

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

БМВ,вы знаете был косяк, с «/с», только сейчас понял что раскладка была русская,
поставил «/с» на место, возвращает статус 1, но все равно не копирует.
такие заморочки возникли потому что на машина, которая копирует файл с сетевого ресурса, не в домене, первоначально использованный Shell вроде как помог решить эту проблему

 

БМВ

Модератор

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

Excel 2013, 2016

jfd, Вы сперва проверьте что за COPY …. вы подсовываете после вставки значений переменных, проверьте выполнение этой команды просто руками. Если машина не в домене, то возможно просто нет доступа. Аутентификация то не пройдена, конечно если перед этим к ресурсу не обращались и не ввели доменный пароль.

По вопросам из тем форума, личку не читаю.

 

jfd

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

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

БМВ,ваш совет помог. файл копируется, выдает статус 0.

Спасибо

 

БМВ

Модератор

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

Excel 2013, 2016

#13

07.07.2018 11:32:59

Не знаю, будете ли вы контролировать статус, но по идее достаточно

Код
CreateObject("WScript.Shell").Run "cmd copy updFilePath & updFileArr(i), fnSyn", 0, True

По вопросам из тем форума, личку не читаю.

 

jfd

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

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

#14

07.07.2018 12:58:59

БМВ, у меня затык вышел с тем что переменные были в кавычках и читались как текст, в вашем последнем примере такая же история

Код
WshShell.Run("cmd /c copy " & updFilePath & updFileArr(i) & ", " & fnSyn, 1, True)
 

БМВ

Модератор

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

Excel 2013, 2016

#15

07.07.2018 13:13:24

jfd,  Вы правы, но я на это не обращал внимание, больше про SHELL писал Я больше скажу, для универсальности кавычек не хватает, если в пути будет пробел, то путь будет воспринят не верно

лучше так

Код
CreateObject("WScript.Shell").Run "cmd /c copy """ & updFilePath & updFileArr(i) & """, """ & fnSyn & """ , 0 true

По вопросам из тем форума, личку не читаю.

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.

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

Понравилась статья? Поделить с друзьями:
  • Vba excel закрыть ячейку
  • Vba excel добавление строк в таблицу
  • Vba excel закрыть файл с сохранением
  • Vba excel закрыть файл word
  • Vba excel добавление новых строк