I need help writing a keyboard event handler in VBA.

I need help writing a keyboard event handler in VBA.

I’m trying to write a macro that will interact with the mouse and keyboard. I found a GREAT forum post where Josh Brady posted some code that works great with the mouse using GetMouse. In this example, if the mouse is clicked, a dialog comes up with the mouse position (X, Y). I’d like to add a listener to it where it listens for a keyboard click as well. For example, if a key is pressed and that key is ESC, then it will end the macro.

Here’s a link to the post where Josh Brady’s shared his code. It’s a MUST READ for anyone who is trying to learn how to handle the mouse.

“Help with mouse clicks”
https://r1132100503382-eu1-3dswym.3dexperience.3ds.com/#community:yUw32GbYTEqKdgY7-jbZPg/iquestion:MsVW4F7VS52LmDUWtXrSog

SendKeys should be the key you looking for. Check codes by @Josh here https://r1132100503382-eu1-3dswym.3dexperience.3ds.com/#community:yUw32GbYTEqKdgY7-jbZPg/iquestion:cPZa4KkjSHKVJEaLiC692g

Deepak,
Thank you for your response. The Microsoft VBA reference says that SendKeys “Sends one or more keystrokes to the active window as if typed at the keyboard.”

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/sendkeys-statement

I’m not sure how I could use “SendKeys” to LISTEN for keystrokes.

Sorry, I went the other way round. Check the macro codes here https://wellsr.com/vba/2017/excel/GetAsyncKeyState-vba-to-wait-until-a-key-is-pressed/

Nice! I’ll check that out.