Is there a way to impose a time limit for the code in VBA?

前端 未结 1 1778
日久生厌
日久生厌 2021-01-27 07:46

I was wondering if anyone had any experience imposing time limits on sections of code. I have programmed a search engine into an excel spreadsheet in VBA and there is a section

相关标签:
1条回答
  • 2021-01-27 08:04

    I assume your code must have some kind of loop, e.g. For Each, While ... Wend, Do ... Loop Until, etc.

    In theses cases, extend the condition by a comparison to the Timer. This returns you a Double between 0 and 86400, indicating how many seconds have passed since midnight. Thus, you also need to account for the day break. Here is some example code showing you implementations for three different loop constructs:

    Sub ExampleLoops()
        Dim dblStart As Double
        Dim tmp As Long
    
        Const cDblMaxTimeInSeconds As Double = 2.5
    
        dblStart = Timer
    
        'Example with For loop
        For tmp = 1 To 1000
            tmp = 1     'to fake a very long loop, replace with your code
            DoEvents    'your code here
            If TimerDiff(dblStart, Timer) > cDblMaxTimeInSeconds Then GoTo Finalize 'Alternative: Exit For
        Next
    
        'Alternative example for Do loop
        Do
            DoEvents 'your code here
        Loop Until TimerDiff(dblStart, Timer) > cDblMaxTimeInSeconds And False 'your condition here
    
        'Alternative example for While loop
        While TimerDiff(dblStart, Timer) <= cDblMaxTimeInSeconds And True 'your condtion here
            DoEvents 'your code here
        Wend
    
    Finalize:
        'FinalizeCode here
        Exit Sub
    End Sub
    
    Function TimerDiff(dblTimerStart As Double, dblTimerEnd As Double)
        Dim dblTemp As Double
        dblTemp = dblTimerEnd - dblTimerStart
        If dblTemp < -43200 Then 'half a day
            dblTemp = dblTemp + 86400
        End If
        TimerDiff = dblTemp
    End Function
    
    0 讨论(0)
提交回复
热议问题