Absolutely cannot run any macro after SetTimer fun

2019-09-02 06:38发布

So I need to use the SetTimer API in my Excel VB project, but after I execute the interval timer, the program crashes as soon as you attempt to run another macro. Even when simply clicking the macro button in Developer tab. The code:

Public Declare Function SetTimer Lib "user32" ( _
    ByVal HWnd As Long, _
    ByVal nIDEvent As Long, _
    ByVal uElapse As Long, _
    ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" ( _
    ByVal HWnd As Long, _
    ByVal nIDEvent As Long) As Long

Public timId As Long, lala As Long, i As Integer

Public Sub CallTm()

timId = SetTimer(0, 0, 100, AddressOf Test)

End Sub
Public Sub AnotherSub()

MsgBox "This is not gonna be shown"

End Sub

Public Sub Test()

Cells(1, 1).Value = i
i = i + 1

End Sub

It seems it's not a problem with KillTimer. Simply setting the interval with SetTimer is like a switch for making sure no more macros can be run (or it will simply crash if you attempt that). I remember seeing Error 50290 if that's any more help.

Why is it so and how can it be fixed?

By the way, I'm making a snake game in Excel for a school project.

It seems like after the Timer is set, nothing can happen since the timer takes up all the thread? or smth like that and it can't be "interrupted".

Really, how is this API supposed to be used? It seems like a fatal error which makes it completely useless...

2条回答
Luminary・发光体
2楼-- · 2019-09-02 06:59

You're corrupting the stack, because your Test procedure does not match the signature of TimerProc. You should read and understand the documentation for API calls before simply making a blind stab at using them.

You can find the documentation for SetTimer at MSDN as well, just like all other WinAPI documentation.

查看更多
何必那么认真
3楼-- · 2019-09-02 06:59

the prototype of timerPorc is this

VOID CALLBACK TimerProc(
  _In_ HWND     hwnd,
  _In_ UINT     uMsg,
  _In_ UINT_PTR idEvent,
  _In_ DWORD    dwTime
);

that can be translated to vb as follow

sub Test(byval hWnd as long, byval uMsg as long,byval idIvent as long, byval dwTime as long)

    'your code here

end sub
查看更多
登录 后发表回答