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
Excel VBA: interrupt code execution (not by hitting 'escape')
提问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 DoEvents
in 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 ButtonClick
to the button. Main
will 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