Delay macro to allow events to finish

Instead I implemented the delay using the functions Now and DateAdd:

Function Delay(Seconds As Long)
    Dim StopTime As Date: StopTime = DateAdd("s", Seconds, Now)
    Do While Now < StopTime
        DoEvents
    Loop
End Function

Updated below for millisecond precision

Function Delay(Seconds As Double)
    Dim StopTime As Double: StopTime = Timer + Seconds
    Do While Timer < StopTime
        DoEvents
    Loop
End Function

For asynchronous events, the following may work but is currently untested

Function DelayForAsync()
    Dim CalculationState As Long
    With Application
        CalculationState = .Calculation
        .Calculation = xlCalculationAutomatic
        .CalculateUntilAsyncQueriesDone
        Do Until .CalculationState = xlDone
            DoEvents
        Loop
        .Calculation = CalculationState
    End With
End Function

Leave a Comment