How to give a time delay of less than one second in excel vba?

后端 未结 10 2146
孤街浪徒
孤街浪徒 2020-11-29 06:14

i want to repeat an event after a certain duration that is less than 1 second. I tried using the following code

Application.wait Now + TimeValue (\"00:00:01\         


        
10条回答
  •  天命终不由人
    2020-11-29 06:55

    Everyone tries Application.Wait, but that's not really reliable. If you ask it to wait for less than a second, you'll get anything between 0 and 1, but closer to 10 seconds. Here's a demonstration using a wait of 0.5 seconds:

    Sub TestWait()
      Dim i As Long
      For i = 1 To 5
        Dim t As Double
        t = Timer
        Application.Wait Now + TimeValue("0:00:00") / 2
        Debug.Print Timer - t
      Next
    End Sub
    

    Here's the output, an average of 0.0015625 seconds:

    0
    0
    0
    0.0078125
    0
    

    Admittedly, Timer may not be the ideal way to measure these events, but you get the idea.

    The Timer approach is better:

    Sub TestTimer()
      Dim i As Long
      For i = 1 To 5
        Dim t As Double
        t = Timer
        Do Until Timer - t >= 0.5
          DoEvents
        Loop
        Debug.Print Timer - t
      Next
    End Sub
    

    And the results average is very close to 0.5 seconds:

    0.5
    0.5
    0.5
    0.5
    0.5
    

提交回复
热议问题