Application.wait 在 VBA

Application.wait in VBA

我想在我的应用程序中添加 1 秒的等待时间。


我在网上找到了什么?

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

这是我的代码

Sub workwithdelay()
Dim i As Integer
Dim done As Integer
Dim newHour As Integer
Dim newMinute As Integer
Dim newSecond As Integer
Dim waitTime As String
Dim ws As Worksheet


Set ws = ActiveSheet

frame = Cells(1, "A").Value


For i = 1 To done

newHour = Hour(Now)
newMinute = Minute(Now)
newSecond = second(Now) + 1
waitTime = newHour: newMinute: newSecond

(ALL of work Code)

Application.Wait waitTime

Next i

End Sub

代码在for循环中完成一个循环(不包括等待时间)需要0.30秒到0.45秒,具体取决于数据的处理。无论循环的处理时间是多少,我都想添加一个确定的 1 秒来完成一个 for 循环。

您需要对 do...loop + timer 使用不同的技术。

Sub WaitOneSecond()

    Dim Start as single
        start = timer
    do while start + 1 > timer
       doevents
    loop
end sub

并在您的原始子调用中 WaitOnSecond 必要时:

Sub workwithdelay()
(...)

For i = 1 To done
(...)
call WaitOnSecond

Next i

End Sub

上面的一些信息:

  1. timer 从今天的午夜开始计算秒数和毫秒数
  2. 请注意我的代码 运行 就在午夜之前-新的一天开始时它是不正确的
  3. application.wait 无法识别毫秒,因此您无法获得准确的 1 秒等待时间

你的想法是对的,但我认为你想要的是TimeValue函数(documented here)。

你可以这样使用它:

Dim StartTime as Date
Dim EndTime as Date

StartTime =  Now
EndTime = StartTime + TimeValue("00:00:01")
' Do Stuff
Application.Wait EndTime

这将导致应用程序在 Do Stuff 部分的 start 之后等待一秒钟,我认为这正是您所要求的。

希望这对您有所帮助:)