【问题标题】:How to deal with "runtime error 50290" when using SetTimer API?使用 SetTimer API 时如何处理“运行时错误 50290”?
【发布时间】:2015-09-19 14:28:20
【问题描述】:

我在 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 崩溃。

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

【问题讨论】:

    标签: vba excel timer crash


    【解决方案1】:

    我能够解决它

    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
    

    【讨论】:

    【解决方案2】:

    我发现对当前时间使用 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
    

    【讨论】:

      猜你喜欢
      • 2019-06-23
      • 2020-01-22
      • 2015-06-05
      • 1970-01-01
      • 2015-12-06
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多