Vba excel ожидание 5 секунд

Complete Guide to Pausing VBA Execution

Background Information and Explanation

All Microsoft Office applications run VBA code in the same thread as the main user interface. This means, as long as the VBA code doesn’t call DoEvents, code execution freezes the entire application (It will show as «not responding» in Task-Manager!). This includes calls to the Sleep API function. Once Sleep is called, there is no way of recovering from this state without waiting for the time to pass or force quitting the Application and restarting it.

The Excel-specific Application.Wait also suffers from this issue, except that the app will not show as not responding in Task Manager in this case. It will still be just as unresponsive to the user.

A way to circumvent this problem is calling DoEvents in a loop, as other people have already pointed out. However, this comes with another issue. Because the application will try to execute VBA code as fast as possible, DoEvents is called at the maximum achievable rate essentially saturating the CPU completely on that single thread, leading to high, unnecessary CPU and power usage and potentially slowing down other more important tasks in the UI.

This is why the best way of getting VBA to pause execution is a combination of both methods, using DoEvents to stay responsive and Sleep to avoid maximum CPU usage. An implementation of this is presented in the following.


Universal Solution

The following code implements a WaitSeconds Sub that will pause execution for a given amount of seconds while avoiding all of the above-mentioned issues.
It can be used like this:

Sub UsageExample()
    WaitSeconds 3.5
End Sub

This will pause the macro for 3.5 seconds, without freezing the application or causing excessive CPU usage. For this to work, just copy the following code to the top of any standard code module.

#If Mac Then
    #If VBA7 Then
        Private Declare PtrSafe Sub USleep Lib "/usr/lib/libc.dylib" Alias "usleep" (ByVal dwMicroseconds As Long)
    #Else
        Private Declare Sub USleep Lib "/usr/lib/libc.dylib" Alias "usleep" (ByVal dwMicroseconds As Long)
    #End If
#Else
    #If VBA7 Then
        Private Declare PtrSafe Sub MSleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)
    #Else
        Private Declare Sub MSleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)
    #End If
#End If

'Sub providing a Sleep API consistent with Windows on Mac (argument in ms)
'Authors: Guido Witt-Dörring, https://stackoverflow.com/a/74262120/12287457
'         Cristian Buse,      https://stackoverflow.com/a/71176040/12287457
Public Sub Sleep(ByVal dwMilliseconds As Long)
    #If Mac Then 'To avoid overflow issues for inputs > &HFFFFFFFF / 1000:
        Do While dwMilliseconds And &H80000000
            USleep &HFFFFFED8
            If dwMilliseconds < (&H418937 Or &H80000000) Then
                dwMilliseconds = &H7FBE76C9 + (dwMilliseconds - &H80000000)
            Else: dwMilliseconds = dwMilliseconds - &H418937: End If
        Loop
        Do While dwMilliseconds > &H418937
            USleep &HFFFFFED8: dwMilliseconds = dwMilliseconds - &H418937
        Loop
        If dwMilliseconds > &H20C49B Then
            USleep (dwMilliseconds * 500& Or &H80000000) * 2&
        Else: USleep dwMilliseconds * 1000&: End If
    #Else
        MSleep dwMilliseconds
    #End If
End Sub

'Sub pausing code execution without freezing the app or causing high CPU usage
'Author: Guido Witt-Dörring, https://stackoverflow.com/a/74387976/12287457
Public Sub WaitSeconds(ByVal seconds As Single)
    Dim currTime As Single:  currTime = Timer()
    Dim endTime As Single:   endTime = currTime + seconds
    Dim cacheTime As Single: cacheTime = currTime
    Do While currTime < endTime
        Sleep 15: DoEvents: currTime = Timer() 'Timer function resets at 00:00!
        If currTime < cacheTime Then endTime = endTime - 86400! '<- sec per day
        cacheTime = currTime
    Loop
End Sub

[1] More information on the cross-platform Sleep included in the above code can be found here and here.

If application freezing is not an issue, e.g. for very short delays or if user interaction is undesired, the best solution is to call Sleep directly. This is why, in the above solution, it is also declared as Public. Note that Sleep takes its argument as milliseconds.

'Does freeze application
Sub UsageExample()
    Sleep 3.5 * 1000
End Sub

Important Notes:

  1. The time precision of the Timer() function used in this solution is better on Windows, however, the claim in the documentation, that resolution on Mac is one second, is wrong. Even on Mac, the resolution is better than 0.1 seconds. Still, you shouldn’t expect a resolution much better than ~0.1 seconds from this solution! WaitSeconds 1 will wait around 1.015 ± 0.02 seconds on Windows.

  2. If you plan on using this to pause your code for long periods of time, or even in a case like OP is dealing with, you are most likely not using the correct tool for the job. If you are using Excel, consider looking into Application.OnTime. (See the following section)


Alternatives to Pausing VBA Execution and Better Solution for OP

The question op has asked does not lead to the best solution for his problem. It’s an XY-Problem.

It is not actually necessary to have VBA code running non-stop in the background in order to recalculate a Workbook every second. This is a typical example of a task that can also be achieved with Application.OnTime.

A detailed guide including a copy-paste solution to recalculate any Range at any desired time interval ≥ 1s is available here.

The big advantage of using Application.OnTime for this is that it avoids a continuously running macro and hence allows the use of other macros or other features that are unavailable while macros are running.


Meta-Analysis of All Other Solutions in This Thread

The reason I even wrote this answer is that all other solutions presented in this thread (at the time this post was written) have at least one of the following two severe drawbacks:

  1. They freeze the calling application completely, causing it to no longer respond to user input, or
  2. They cause excessive CPU usage (100% on the calling application’s thread) by calling DoEvents in a loop.

Additionally, many of the proposed solutions have other issues:

  1. Some only work on Windows

  2. Some only work in Excel

  3. Some have an intrinsic imprecision of more than one second

  4. Some have other problems or even bugs

The following table will give a short overview of all the solutions in this thread and their features

Legend

Column ✅ (Good) ❌ (Bad)
App Responds App stays responsive and usable Freezes calling app completely
CPU Usage Practically no CPU usage 100% CPU usage in the single executing thread
Cross-App Works outside Excel Works only in Excel
Win/Mac Works on both, Windows and Mac Only works on Windows
Precise Time precision < 0.1 seconds Time precision > 0.1 seconds (usually about 1 second)
Other Issues No other issues Has some other issues described in the table below

Overview

Other issues

Solution by Other issues
cyberpunk This solution will sleep indefinitely if at the time of calling Timer() + vSeconds > 172800 (vSevonds is the input value). In practice, this shouldn’t be a big problem because Timer() is always ≤ 86400 so the input value needs to be bigger than 86400 which is one day. Such functions usually shouldn’t be called for such long times anyways.
Reverus This solution doesn’t allow pausing for a specific amount of time at all! You just specify how often you want to call DoEvents before continuing. How long this is, depends on the speed of your system. On my PC, calling the function with the maximum value a Long can take (2147483647) (so the maximum time the function can pause) will pause for about 1434 seconds or about 24 minutes. Obviously, this is a terrible «solution».
Brian Burns This solution will sleep indefinitely if at the time of calling Timer() + sngSecs > 86400 (sngSecs is the input value). Because Timer() can return values up to 86400, calling this function right before midnight can cause this bug even with very small input values. This is a severe bug and should be considered!
g t This solution does not wait at all. If you consider its generalization, Application.Wait Second(Now) + dblInput, it will not wait at all for input values smaller than CDbl(Now) - 60# / 86400#, which is 44815 at the time of writing this, and for input values larger than that, it will wait for dblInput - CDbl(Now) - Second(Now) / 86400# days. While input values can be constructed that will make this wait for a reasonable amount of time, this is very difficult. A terrible «solution».
ITI The comment describes this function as being able to cause delays of up to 99 seconds. This is wrong because input values where T Mod 100 > 60(T is the input parameter) will cause an error and hence stop execution indefinitely if the error is not handled by the calling code. You can confirm this by calling the function like this: Delay 61
dave This solution will work correctly but additionally sets Application.EnableEvents = True for no reason at all. If the calling code set this property to False and reasonably doesn’t expect a function that has nothing to do with this to set it to True, this can lead to severe bugs in the calling code. If that line is deleted, the solution is fine.

Complete Guide to Pausing VBA Execution

Background Information and Explanation

All Microsoft Office applications run VBA code in the same thread as the main user interface. This means, as long as the VBA code doesn’t call DoEvents, code execution freezes the entire application (It will show as «not responding» in Task-Manager!). This includes calls to the Sleep API function. Once Sleep is called, there is no way of recovering from this state without waiting for the time to pass or force quitting the Application and restarting it.

The Excel-specific Application.Wait also suffers from this issue, except that the app will not show as not responding in Task Manager in this case. It will still be just as unresponsive to the user.

A way to circumvent this problem is calling DoEvents in a loop, as other people have already pointed out. However, this comes with another issue. Because the application will try to execute VBA code as fast as possible, DoEvents is called at the maximum achievable rate essentially saturating the CPU completely on that single thread, leading to high, unnecessary CPU and power usage and potentially slowing down other more important tasks in the UI.

This is why the best way of getting VBA to pause execution is a combination of both methods, using DoEvents to stay responsive and Sleep to avoid maximum CPU usage. An implementation of this is presented in the following.


Universal Solution

The following code implements a WaitSeconds Sub that will pause execution for a given amount of seconds while avoiding all of the above-mentioned issues.
It can be used like this:

Sub UsageExample()
    WaitSeconds 3.5
End Sub

This will pause the macro for 3.5 seconds, without freezing the application or causing excessive CPU usage. For this to work, just copy the following code to the top of any standard code module.

#If Mac Then
    #If VBA7 Then
        Private Declare PtrSafe Sub USleep Lib "/usr/lib/libc.dylib" Alias "usleep" (ByVal dwMicroseconds As Long)
    #Else
        Private Declare Sub USleep Lib "/usr/lib/libc.dylib" Alias "usleep" (ByVal dwMicroseconds As Long)
    #End If
#Else
    #If VBA7 Then
        Private Declare PtrSafe Sub MSleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)
    #Else
        Private Declare Sub MSleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)
    #End If
#End If

'Sub providing a Sleep API consistent with Windows on Mac (argument in ms)
'Authors: Guido Witt-Dörring, https://stackoverflow.com/a/74262120/12287457
'         Cristian Buse,      https://stackoverflow.com/a/71176040/12287457
Public Sub Sleep(ByVal dwMilliseconds As Long)
    #If Mac Then 'To avoid overflow issues for inputs > &HFFFFFFFF / 1000:
        Do While dwMilliseconds And &H80000000
            USleep &HFFFFFED8
            If dwMilliseconds < (&H418937 Or &H80000000) Then
                dwMilliseconds = &H7FBE76C9 + (dwMilliseconds - &H80000000)
            Else: dwMilliseconds = dwMilliseconds - &H418937: End If
        Loop
        Do While dwMilliseconds > &H418937
            USleep &HFFFFFED8: dwMilliseconds = dwMilliseconds - &H418937
        Loop
        If dwMilliseconds > &H20C49B Then
            USleep (dwMilliseconds * 500& Or &H80000000) * 2&
        Else: USleep dwMilliseconds * 1000&: End If
    #Else
        MSleep dwMilliseconds
    #End If
End Sub

'Sub pausing code execution without freezing the app or causing high CPU usage
'Author: Guido Witt-Dörring, https://stackoverflow.com/a/74387976/12287457
Public Sub WaitSeconds(ByVal seconds As Single)
    Dim currTime As Single:  currTime = Timer()
    Dim endTime As Single:   endTime = currTime + seconds
    Dim cacheTime As Single: cacheTime = currTime
    Do While currTime < endTime
        Sleep 15: DoEvents: currTime = Timer() 'Timer function resets at 00:00!
        If currTime < cacheTime Then endTime = endTime - 86400! '<- sec per day
        cacheTime = currTime
    Loop
End Sub

[1] More information on the cross-platform Sleep included in the above code can be found here and here.

If application freezing is not an issue, e.g. for very short delays or if user interaction is undesired, the best solution is to call Sleep directly. This is why, in the above solution, it is also declared as Public. Note that Sleep takes its argument as milliseconds.

'Does freeze application
Sub UsageExample()
    Sleep 3.5 * 1000
End Sub

Important Notes:

  1. The time precision of the Timer() function used in this solution is better on Windows, however, the claim in the documentation, that resolution on Mac is one second, is wrong. Even on Mac, the resolution is better than 0.1 seconds. Still, you shouldn’t expect a resolution much better than ~0.1 seconds from this solution! WaitSeconds 1 will wait around 1.015 ± 0.02 seconds on Windows.

  2. If you plan on using this to pause your code for long periods of time, or even in a case like OP is dealing with, you are most likely not using the correct tool for the job. If you are using Excel, consider looking into Application.OnTime. (See the following section)


Alternatives to Pausing VBA Execution and Better Solution for OP

The question op has asked does not lead to the best solution for his problem. It’s an XY-Problem.

It is not actually necessary to have VBA code running non-stop in the background in order to recalculate a Workbook every second. This is a typical example of a task that can also be achieved with Application.OnTime.

A detailed guide including a copy-paste solution to recalculate any Range at any desired time interval ≥ 1s is available here.

The big advantage of using Application.OnTime for this is that it avoids a continuously running macro and hence allows the use of other macros or other features that are unavailable while macros are running.


Meta-Analysis of All Other Solutions in This Thread

The reason I even wrote this answer is that all other solutions presented in this thread (at the time this post was written) have at least one of the following two severe drawbacks:

  1. They freeze the calling application completely, causing it to no longer respond to user input, or
  2. They cause excessive CPU usage (100% on the calling application’s thread) by calling DoEvents in a loop.

Additionally, many of the proposed solutions have other issues:

  1. Some only work on Windows

  2. Some only work in Excel

  3. Some have an intrinsic imprecision of more than one second

  4. Some have other problems or even bugs

The following table will give a short overview of all the solutions in this thread and their features

Legend

Column ✅ (Good) ❌ (Bad)
App Responds App stays responsive and usable Freezes calling app completely
CPU Usage Practically no CPU usage 100% CPU usage in the single executing thread
Cross-App Works outside Excel Works only in Excel
Win/Mac Works on both, Windows and Mac Only works on Windows
Precise Time precision < 0.1 seconds Time precision > 0.1 seconds (usually about 1 second)
Other Issues No other issues Has some other issues described in the table below

Overview

Other issues

Solution by Other issues
cyberpunk This solution will sleep indefinitely if at the time of calling Timer() + vSeconds > 172800 (vSevonds is the input value). In practice, this shouldn’t be a big problem because Timer() is always ≤ 86400 so the input value needs to be bigger than 86400 which is one day. Such functions usually shouldn’t be called for such long times anyways.
Reverus This solution doesn’t allow pausing for a specific amount of time at all! You just specify how often you want to call DoEvents before continuing. How long this is, depends on the speed of your system. On my PC, calling the function with the maximum value a Long can take (2147483647) (so the maximum time the function can pause) will pause for about 1434 seconds or about 24 minutes. Obviously, this is a terrible «solution».
Brian Burns This solution will sleep indefinitely if at the time of calling Timer() + sngSecs > 86400 (sngSecs is the input value). Because Timer() can return values up to 86400, calling this function right before midnight can cause this bug even with very small input values. This is a severe bug and should be considered!
g t This solution does not wait at all. If you consider its generalization, Application.Wait Second(Now) + dblInput, it will not wait at all for input values smaller than CDbl(Now) - 60# / 86400#, which is 44815 at the time of writing this, and for input values larger than that, it will wait for dblInput - CDbl(Now) - Second(Now) / 86400# days. While input values can be constructed that will make this wait for a reasonable amount of time, this is very difficult. A terrible «solution».
ITI The comment describes this function as being able to cause delays of up to 99 seconds. This is wrong because input values where T Mod 100 > 60(T is the input parameter) will cause an error and hence stop execution indefinitely if the error is not handled by the calling code. You can confirm this by calling the function like this: Delay 61
dave This solution will work correctly but additionally sets Application.EnableEvents = True for no reason at all. If the calling code set this property to False and reasonably doesn’t expect a function that has nothing to do with this to set it to True, this can lead to severe bugs in the calling code. If that line is deleted, the solution is fine.

Содержание

  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 Wait & Sleep Functions – Pause / Delay VBA Code
  16. Use of Application.Wait Method
  17. Wait 1 Second
  18. Wait Until
  19. Use of Sleep Method
  20. Using a Loop with Do Events
  21. VBA Coding Made Easy
  22. VBA Code Examples Add-in
  23. Функция ожидания VBA
  24. Функция ожидания Excel VBA
  25. Примеры использования функции ожидания Excel VBA
  26. VBA Sleep против VBA Ожидание
  27. Рекомендуемые статьи
  28. VBA Application.Wait to Pause for Specific Time
  29. The VBA Tutorials Blog
  30. Introduction — VBA Application.Wait
  31. Example — VBA Application.Wait
  32. Pausing your macro for a certain number of seconds
  33. Tutorial — VBA Application.Wait
  34. Big Picture
  35. TimeValue argument
  36. Application Ideas — VBA Application.Wait

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 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

Функция ожидания 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 Application.Wait to Pause for Specific Time

The VBA Tutorials Blog

Introduction — VBA Application.Wait

Use the VBA Application.Wait method to pause your macro for a specific amount of time. Application.Wait is a simple way to delay your macro by a fixed number of seconds.

This isn’t the first tutorial I’ve posted about how to pause your macro. A few months ago I told you how to use VBA Sleep to add a time delay to your macro.

While VBA Sleep is still my favorite method for pausing a macro, it’s a bit more complicated than Application.Wait. When you know you’ll be pausing for more than 1 second, the Application.Wait method is a great way to do it because it’s easy to remember!

Stick with me and I’ll show you how it works.

Example — VBA Application.Wait

Pausing your macro for a certain number of seconds

Make powerful macros with our free VBA Developer Kit

It’s easy to copy and paste a macro like this, but it’s harder make one on your own. To help you make macros like this, we built a free VBA Developer Kit and wrote the Big Book of Excel VBA Macros full of hundreds of pre-built macros to help you master file I/O, arrays, strings and more — grab your free copy below.

Tutorial — VBA Application.Wait

Big Picture

Do you remember when I said Application.Wait was easy to remember? Well, I wasn’t kidding. There’s really not much left for me to explain!

The VBA Application.Wait method only accepts one argument: time. To wait 5 seconds, like I did in the demo above, you feed Application.Wait the current time with the Now function. Then, you use the TimeValue function to add 5 seconds to the current time. Once the 5 seconds elapses, your macro will continue. In the example demo, that means you’ll get a MsgBox telling you it’s been 5 seconds.

TimeValue argument

The syntax of the TimeValue function is the most difficult piece to remember. The TimeValue function converts a string to a time. Well, technically it returns the serial number equivalent of the time, but that’s beside the point. All you need to know is that, for the purposes of delaying your macro, your string should be entered in a format like hh:mm:ss, where hh represents hours, mm represents minutes, and ss represents seconds.

Because the TimeValue function accepts arguments in the “hh:mm:ss” format, you’re not able to use it to pause your macro for less than 1 second. You would need to use the VBA Sleep function if you want pauses for fractions of a second.

The important thing to remember is that, if you want to delay your macro by a specific amount of time, you must add the results of the TimeValue function to the current time calculated using the Now function, like I did in the example macro. Otherwise, your macro could be paused until the middle of the night!

Don’t worry, if you accidentally use the wrong syntax, you can stop your macro with the Esc key or the Break key.

Application Ideas — VBA Application.Wait

To inspire you, here are a few examples where I used the VBA Application.Wait method on the VBA Tutorials Blog:

These are actually some of my most popular posts. Are they the most popular because I used Application.Wait? Probably not, but who knows! Maybe when you use Application.Wait, you’ll be popular, too! 😉

How do you plan on using the VBA Application.Wait method? It really can be quite helpful!

When you’re done, please share this article with your friends on Facebook and Twitter. Sharing articles with others is how wellsr.com will continue to grow, so I genuinely appreciate it.

When you’re ready to free up your time in the office, subscribe using the form below.

Ready to do more with VBA?
We put together a giant PDF with over 300 pre-built macros and we want you to have it for free. Enter your email address below and we’ll send you a copy along with our VBA Developer Kit, loaded with VBA tips, tricks and shortcuts.

Before we go, I want to let you know we designed a suite of VBA Cheat Sheets to make it easier for you to write better macros. We included over 200 tips and 140 macro examples so they have everything you need to know to become a better VBA programmer.

Источник

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!

Функция ожидания 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

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