使用SetTimer API时如何处理"runtime error 50290"?

How to deal with "runtime error 50290" when using SetTimer API?

我在 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

然后单击按钮并开始单击随机单元格。很快你会得到以下 window:

然后 Excel 崩溃。

我做错了什么?
如何处理?

我用

解决了这个问题
On Error Resume Next

TimerProc的开头。一些 more (in Russian) or less related 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

我发现将 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