Excel VBA:中断代码执行(不是通过点击“转义”)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9580330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 15:28:07  来源:igfitidea点击:

Excel VBA: interrupt code execution (not by hitting 'escape')

excelexcel-vbavba

提问by Pieter

I have a Do .. While loop in which two For.. loops are nested; the first For.. loop counts up from 1 to X, the second loop counts down from X to 1. This is currently repeated ad infinitum.

我有一个 Do .. While 循环,其中嵌套了两个 For.. 循环;第一个 For.. 循环从 1 向上计数到 X,第二个循环从 X 向下计数到 1。这是目前无限重复的。

Now, I want the user to be able to 'interrupt' this infinite loop, and that the program, upon interruption of the loop, executes XYZ.

现在,我希望用户能够“中断”这个无限循环,并且程序在循环中断时执行 XYZ。

I've tried using a toggle button in combination with the Do.. While loop, but while the aforementioned loop is running, no input is accepted. The state of the button does not change when clicked if the code is running the loop.

我尝试将切换按钮与 Do..While 循环结合使用,但是在上述循环运行时,不接受任何输入。如果代码正在运行循环,按钮的状态在单击时不会改变。

Any suggestions are highly appreciated.

任何建议都非常感谢。

回答by chris neilsen

The key is to include a DoEventsin the loops. This allows Excel to process things like a button click while running the code

关键是DoEvents在循环中包含 a 。这允许 Excel 在运行代码时处理诸如单击按钮之类的事情

Here's an outline. Assign macro ButtonClickto the button. Mainwill run indefinately until the button is clicked.

这是一个大纲。将宏分配ButtonClick给按钮。 Main将无限期运行,直到单击该按钮。

Option Explicit
Dim bBreak As Boolean

Sub ButtonClick()
    bBreak = True

End Sub

Sub Main()
    Dim X As Long
    Dim i As Long
    bBreak = False

    Do While True
        X = 1000
        For i = 1 To X
            If bBreak Then
                Exit Do
            End If
            DoEvents
        Next

        For i = X To 1 Step -1
            If bBreak Then
                Exit Do
            End If
            DoEvents
        Next
    Loop
    If bBreak Then XYZ
End Sub