Reputation: 127
I have several subs which call onto each other when a OnKey event is pressed. After a while, the call stack builds up and i get a "out of stack" error. Is there a method to clear the stack? Or at least end the sub when I'm not using it? EG.
Sub MoveRight()
if GetKeyState(vbKeyDown) <0 then MoveDown
...
...
sub MoveDown
if GetKeyState(vbKeyRight) < 0 then MoveRight
...
...
etc
Upvotes: 1
Views: 572
Reputation: 31
Code shown is a bit criptic, but, if you press "down" and "right" at same time, your code do a circular call between subs, that is a loop of calls that never ever returns, so stack will overflows in seconds. It will better to check keys outside subs (pseudocode):
if (key_down is pressed)
call do_move_down
if (key_right is pressed)
call do_move_right
...
...
Upvotes: 3
Reputation: 56745
"Out of Stack" is a Severe Fatal error. The way to clear it is to restart Excel. Though it is possible that just restarting VBA would be sufficient, I sure wouldn't trust it.
The problem here is that you have written a pair of methods with infinite recursion in them. DON'T DO THAT. The simplest general fix to this is to have your routines set static flags to prevent re-entry:
Sub MoveRight()
Static InUse As Boolean
If InUse Then Exit Sub
InUse = True
if GetKeyState(vbKeyDown) <0 then MoveDown
...
...
InUse = False
End Sub
A more specific fix would require knowledge of what you are actually trying to do, which looks highly suspect at this point.
Upvotes: 3
Reputation: 381
You are calling into your MoveRight()
and MoveDown()
methods recursively.
You test calls to GetKeyState
should sit outside of your stubs / event handlers.
A wider question might be why you need these calls at all if you already have the OnKey
event correctly configured.
Upvotes: 0