Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here


Get Keystroke Within Loop

Get Keystroke Within Loop

Get Keystroke Within Loop

If I want a procedure to run every time a specific key is pressed, I would use the code:


My problem is that if "Key" is pressed while a Sub is running, it won't be processed to after the Sub completes.  What I would like to do is have a Sub that is running react to a keystroke.  For instance, in the classic game Nibbles, have a block move up until the left key is pressed, which would cause the block to move to the left, etc.  Any ideas?



RE: Get Keystroke Within Loop

This would be very difficult in VBA as it generally shuts down all user interaction until the code has finished. the only real exception is the ESC key which stops the code

Rgds, Geoff

Never test the depth of water with both feet

Help us to help you by reading FAQ222-2244 before you ask a question

RE: Get Keystroke Within Loop

I figured it out thanks to the magic of open source.  I don't actually understand why it works, but I know that it does work.  In general declarations, include the following code:

Declare Function GetAsyncKeyState Lib "User32.dll" (ByVal vKey As Long) As Long

Const VK_LEFT As Long = &H25

Then create a new function with this code:

    If GetAsyncKeyState(VK_LEFT) <> 0 Then
       MsgBox "Hello!"
       Exit Do
    End If

The if you press the Left key, the function will show the MsgBox and exit the loop.  I'm sure y'all can find some very interesting ways of using this code (personally, I'm going to create an Excel version of Nibbles right now).  


Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close