如何停止VBA代码运行?

假设我的电子表格中embedded了一个button,可以启动一些VBAfunction。

Private Sub CommandButton1_Click() SomeVBASub End Sub Private Sub SomeVBASub DoStuff DoAnotherStuff AndFinallyDothis End Sub 

我想有一个机会,有一种“取消”button,可以在任意时刻停止SomeVBASub执行,而且我不会在这里涉及到Ctrl+Break ,因为我想静静的。

我想这应该是相当普遍的问题,有什么想法?

谢谢。

添加另一个名为“CancelButton”的button来设置一个标志,然后检查该标志。

如果你在“东西”中有很长的循环,那么在那里检查一下,如果设置了就退出。 在长循环内使用DoEvents来确保UI的工作。

 Bool Cancel Private Sub CancelButton_OnClick() Cancel=True End Sub ... Private Sub SomeVBASub Cancel=False DoStuff If Cancel Then Exit Sub DoAnotherStuff If Cancel Then Exit Sub AndFinallyDothis End Sub 

怎么样Application.EnableCancelKey – 使用Escbutton

 On Error GoTo handleCancel Application.EnableCancelKey = xlErrorHandler MsgBox "This may take a long time: press ESC to cancel" For x = 1 To 1000000 ' Do something 1,000,000 times (long!) ' do something here Next x handleCancel: If Err = 18 Then MsgBox "You cancelled" End If 

摘自http://msdn.microsoft.com/zh-cn/library/aa214566(office.11​​).aspx

或者,如果您想避免使用全局variables ,则可以使用userform的很less使用的.Tag属性:

 Private Sub CommandButton1_Click() Me.CommandButton1.Enabled = False 'Disabling button so user cannot push it 'multiple times Me.CommandButton1.caption = "Wait..." 'Jamie's suggestion Me.Tag = "Cancel" End Sub Private Sub SomeVBASub If LCase(UserForm1.Tag) = "cancel" Then GoTo StopProcess Else 'DoStuff End If Exit Sub StopProcess: 'Here you can do some steps to be able to cancel process adequately 'ie setting collections to "Nothing" deleting some files... End Sub 

什么jamietre说,但是

 Private Sub SomeVBASub Cancel=False DoStuff If not Cancel Then DoAnotherStuff If not Cancel Then AndFinallyDothis End Sub 

我做了很多。 很多。 🙂

我已经习惯了使用“DoEvents”,但是仍然倾向于设置事情,而不是真正的双重检查确定的停止方法。

那么,今天又做了一次,我想,“等3个小时才结束吧”,开始在缎带上划。 早些时候,我已经注意到在function区的“视图”部分有一个“macros”拉下来,并认为我看看是否可以看到我的无休止的macros运行….

我现在意识到你也可以使用Alt-F8来解决这个问题。

然后,我想,如果我“步入”一个不同的macros,是否会救我? 它的确如下:-)如果你进入你正在运行的macros(但你仍然失去了自己的位置),它也可以工作,除非你像我这样一个非常懒惰的程序员,并且声明了大量的“Global”variables,在这种情况下,Global数据保留:-)

ķ

〜对于那些使用自定义input框

 Private Sub CommandButton1_Click() DoCmd.Close acForm, Me.Name End End Sub