excel VBA - 通过按 <esc> 停止 运行 的脚本 - 没有错误消息
excel VBA - stop a script that is running by pressing <esc> - without error message
我在 Excel 中有一个脚本有时会 运行 太久。
我需要一个简单的方法让用户中断。
目前的解决方案是按 [esc] 键而不是 [end] 键。
我想知道是否有可能摆脱这个弹出窗口 window
类似于:如果按下 [esc] 而不是简单的 End
(停止所有脚本)就可以解决问题
EDIT3:最后我发现了问题所在。 do while后面有一个for循环,所以for并没有停止。为了解决这个问题,我在 for 循环中插入了一个简单的 if - end 函数。
我也接受 mrbungle 的解决方案,因为在他的 link 中我找到了一个解决方案,可以通过按 [esc] 停止脚本而不会出现错误消息。谢谢你的回答。
工作代码。
Option Explicit
Dim StopCode As Boolean 'Global bool
Sub mysub_Click()
Dim c As Range
Dim p As String
Dim lastonline As Object
Dim x: Dim y
Dim actives As String
Dim timeoutc As Variant
actives = ActiveSheet.Name
timeoutc = 0
StopCode = False
Application.EnableCancelKey = xlErrorHandler
On Error GoTo ErrH:
DoEvents
For Each c In Sheets(actives).UsedRange.Cells
If StopCode = True Then
Exit For
End If
{The code} 'I have deleted it so it is less confusing now
next c
ErrH:
If Err.Number = 18 Then
Debug.Print "break key hit"
Else
Debug.Print "other error: "; Err.Number, Err.Description
End If
End Sub
用户表单
Option Explicit
Dim StopCode As Boolean 'Global bool
Private Sub CommandButton1_Click() 'close button
PTimeout.Hide
End Sub
Private Sub CommandButton2_Click() 'stop script button (does not work)
StopCode = True
PTimeout.Hide
End Sub
Chip Pearson 有一个很好的解决方案 here 我相信它可以解决您的问题。如果 link 被破坏,我将简要解释一下。这将进入您的代码,并在有问题的 sheet 上创建一个命令按钮并分配另一个将 StopCode
设置为 True
的子。当用户单击该按钮时,StopCode
将设置为 True
,代码停止 运行。
StopCode = False
Do Until StopCode = True
DoEvents
' your code here. next line is just an example
我在 Excel 中有一个脚本有时会 运行 太久。 我需要一个简单的方法让用户中断。
目前的解决方案是按 [esc] 键而不是 [end] 键。
我想知道是否有可能摆脱这个弹出窗口 window
类似于:如果按下 [esc] 而不是简单的 End
(停止所有脚本)就可以解决问题
EDIT3:最后我发现了问题所在。 do while后面有一个for循环,所以for并没有停止。为了解决这个问题,我在 for 循环中插入了一个简单的 if - end 函数。
我也接受 mrbungle 的解决方案,因为在他的 link 中我找到了一个解决方案,可以通过按 [esc] 停止脚本而不会出现错误消息。谢谢你的回答。
工作代码。
Option Explicit
Dim StopCode As Boolean 'Global bool
Sub mysub_Click()
Dim c As Range
Dim p As String
Dim lastonline As Object
Dim x: Dim y
Dim actives As String
Dim timeoutc As Variant
actives = ActiveSheet.Name
timeoutc = 0
StopCode = False
Application.EnableCancelKey = xlErrorHandler
On Error GoTo ErrH:
DoEvents
For Each c In Sheets(actives).UsedRange.Cells
If StopCode = True Then
Exit For
End If
{The code} 'I have deleted it so it is less confusing now
next c
ErrH:
If Err.Number = 18 Then
Debug.Print "break key hit"
Else
Debug.Print "other error: "; Err.Number, Err.Description
End If
End Sub
用户表单
Option Explicit
Dim StopCode As Boolean 'Global bool
Private Sub CommandButton1_Click() 'close button
PTimeout.Hide
End Sub
Private Sub CommandButton2_Click() 'stop script button (does not work)
StopCode = True
PTimeout.Hide
End Sub
Chip Pearson 有一个很好的解决方案 here 我相信它可以解决您的问题。如果 link 被破坏,我将简要解释一下。这将进入您的代码,并在有问题的 sheet 上创建一个命令按钮并分配另一个将 StopCode
设置为 True
的子。当用户单击该按钮时,StopCode
将设置为 True
,代码停止 运行。
StopCode = False
Do Until StopCode = True
DoEvents
' your code here. next line is just an example