使用 VBA 在代码执行期间添加延迟
    
    
            Glen Alfaro
    2023年1月30日
    
    VBA
    VBA Delay
    
 
在使用 VBA 处理复杂的计算和过程时,程序员应该记住,有些算法过于繁重,需要一些时间来处理。当当前进程仍在执行时会出现问题,但随后 VBA 编译器会继续执行下一个进程。在这种情况下,会发生溢出和错误。
延迟的典型应用是在处理网络抓取工具时。在抓取数据之前,应先完全加载网站。否则会出现错误。另一个应用是当我们需要在定义的时间范围内定期运行宏时。
本文将演示如何使用 wait 命令添加延迟时间。
语法:
Application.Wait(Now + [delay time])
其中,
| [延迟时间] | 指定所需的延迟时间。 | 
在 VBA 中使用 wait 命令添加延迟时间的示例
Sub DelayMe()
'Print the current time
Debug.Print Now
'Delay for 10 seconds start here
Application.Wait(Now + TimeValue("00:00:10"))
'Print the current time
Debug.Print Now
End Sub
输出:
12/21/2021 4:41:25 PM 
12/21/2021 4:41:35 PM 
使用 wait 命令实现自动更新方案
下面的代码块将演示使用 wait 命令实现自动更新方案。它将每 10 秒调用一次 GetTimeNow 子程序。
Sub AutoUpdate()
'Main loop where the code execution takes place 
Do
'Add a delay for every call
Application.Wait(Now + TimeValue("00:00:10"))
'Calls the GetTimeNow subroutine
Call GetTimeNow
Loop
End Sub
Sub GetTimeNow
'Print the time at the time of the call.
Debug.Print "The current time is: " & Now
End Sub
输出:
The current time is: 12/21/2021 4:59:30 PM
The current time is: 12/21/2021 4:59:48 PM
The current time is: 12/21/2021 5:00:01 PM
The current time is: 12/21/2021 5:00:16 PM
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe