Kir*_*tev 14 excel vba excel-vba
假设我的电子表格中嵌入了一个按钮,可以启动一些VBA功能.
Private Sub CommandButton1_Click()
SomeVBASub
End Sub
Private Sub SomeVBASub
DoStuff
DoAnotherStuff
AndFinallyDothis
End Sub
Run Code Online (Sandbox Code Playgroud)
我想有机会有一个"取消"按钮,可以SomeVBASub在任意时刻停止执行,我不会涉及到Ctrl+Break这里,因为我想默默地这样做.
我想这应该是相当普遍的问题,任何想法?
谢谢.
Jam*_*rgy 20
添加另一个名为"CancelButton"的按钮,用于设置标志,然后检查该标志.
如果你在"东西"中有长循环,那么也检查它,如果已经设置则退出.在长循环中使用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
Run Code Online (Sandbox Code Playgroud)
Application.EnableCancelKey怎么样 - 使用Esc按钮
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
Run Code Online (Sandbox Code Playgroud)
来自http://msdn.microsoft.com/en-us/library/aa214566(office.11).aspx的片段