巧妙捕获用户中断

Sub ESCInterrupt()
Dim i As Long
Cells.ClearContents
For i = 1 To 100000
Cells(i, 1).Value = i
Next i
End Sub

Sub DisbledESC()
Dim i As Long
Dim strTip As String
strTip = “代码运行需要较长时间,是否继续?选择””是””执行,””否””取消。”
Application.EnableCancelKey = xlDisabled
If MsgBox(strTip, vbInformation + vbYesNo) = vbYes Then
Cells.Clear
For i = 1 To 100000
Cells(i, 1).Value = i
Next i
End If
End Sub

Sub ErrorHandleESC()
Dim i As Long
Dim strTip As String
strTip = “代码运行需要较长时间,按 ESC 或 可终止当前代码。”
On Error GoTo HandleCancel
Application.EnableCancelKey = xlErrorHandler
MsgBox strTip, vbExclamation
Cells.Clear
For i = 1 To 100000
Cells(i, 1).Value = i
Next i
Exit Sub
HandleCancel:
If Err.Number = 18 Then
MsgBox “用户终止了代码运行。”, vbExclamation
End If
End Sub

发表回复