Excel VBA:执行中断代码(不是通过点击“转义”) [英] Excel VBA: interrupt code execution (not by hitting 'escape')
问题描述
我有一个Do .. While循环,其中两个For ..循环嵌套;第一个For ..循环从1到X计数,第二个循环从X向下计数到1.这是目前无穷无尽的重复。
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.
现在,我希望用户能够中断这个无限循环,并且程序在循环中断时执行XYZ。
Now, I want the user to be able to 'interrupt' this infinite loop, and that the program, upon interruption of the loop, executes XYZ.
我已经尝试使用与Do .. While循环相结合的切换按钮,但是上述循环正在运行时,不接受输入。如果代码运行循环,按钮的状态不会改变。
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.
高度赞赏任何建议。
推荐答案
关键是在循环中包含一个 DoEvents
这允许Excel在运行代码时处理像点击按钮的东西
The key is to include a DoEvents
in the loops. This allows Excel to process things like a button click while running the code
这是一个大纲。将宏 ButtonClick
分配给按钮。 Main
将一直运行,直到按钮被点击。
Here's an outline. Assign macro ButtonClick
to the button. Main
will run indefinately until the button is clicked.
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
这篇关于Excel VBA:执行中断代码(不是通过点击“转义”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!