vba 循环直到布尔值为假 - 用户窗体按钮

vba loop until boolean is false - userform button

我想在按钮设置为真时一遍又一遍地执行子程序。 我的第一个想法是 while 或 do while 循环,但我不太清楚它是如何正确完成的。在我的例子中 Excel 只是停止 运行.

用户窗体按钮在按下时设置布尔值 "status" true 或 false。如果 "status" 为真,sub 应该在循环中执行。 sub 本身会触发一个计算,将一定数量的钱添加到双 "bank"。如果再次按下同一个按钮,循环应该结束。

Function aktivate(i As Integer)
    array(i).status = True
    call myLoop(i)
End Function


Function deaktivate(i As Integer)
    array(i).status = False
End Function


Function myLoop(i As Integer)
    Do While array(i).status = True
        Call calc(i)

        If array(i).status = False Then Exit Do
    Loop
End Function

您需要在 Do While 循环中使用 DoEvents 以便您可以按下 "Stop" 按钮。如果不这样做,代码将变得无响应并崩溃 excel.

看这个例子

Dim stopLoop As Boolean

Sub StartCode()
    stopLoop = False
    LoopCode
End Sub

Sub StopCode()
    stopLoop = True
End Sub

Sub LoopCode()
    Do While stopLoop = False
        Debug.Print "blah"
        DoEvents
    Loop
End Sub