尝试在Excel中制作秒表计时器时遇到此错误。这是一个简单的测试代码。使用按钮创建一个空的Excel工作簿。并为其指定一个宏:
Sub Button1_Click()
TimerID = SetTimer(0&, 0&, 0.5 * 1000&, AddressOf TimerProc)
End Sub
另外,将此代码添加到模块中:
Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, _
ByVal nIDEvent As Long, _
ByVal uElapse As Long, _
ByVal lpTimerFunc As Long) As Long
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, ByVal nIDEvent As Long, ByVal dwTimer As Long)
Range("A1") = "test"
End Sub
然后单击按钮并开始单击随机单元格。不久,您将看到以下窗口:
然后Excel崩溃了。
我做错了什么? 如何处理?
答案 0 :(得分:0)
我能够用
来解决它On Error Resume Next
在TimerProc
的开头。一些more(俄语)或less相关links。
或者甚至可能更好:
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, ByVal nIDEvent As Long, ByVal dwTimer As Long)
On Error GoTo BeforeExit
Range("A1") = "test"
BeforeExit:
End Sub
答案 1 :(得分:0)
我发现在当前时间使用OnTime会导致您的代码立即在主线程上运行或失败。我发现这更好,因为您只需要捕获OnTime错误即可。
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, ByVal nIDEvent As Long, ByVal
dwTimer As Long)
On Error GoTo BeforeExit
Application.OnTime Now, "updateWorksheet"
BeforeExit:
End Sub
Sub updateWorksheet
Range("A1") = "test"
End Sub