Introduction | Example | Tutorial | Applications | Comments
Introduction - Get Cursor Position
Return your cursor position coordinates with this VBA macro. Play around and use this to map out mouse movements for all your fun macro mouse control scripts.
Get Mouse Position
Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long ' Create custom variable that holds two integers Type POINTAPI Xcoord As Long Ycoord As Long End Type Sub GetCursorPosDemo() Dim llCoord As POINTAPI ' Get the cursor positions GetCursorPos llCoord ' Display the cursor position coordinates MsgBox "X Position: " & llCoord.Xcoord & vbNewLine & "Y Position: " & llCoord.Ycoord End Sub
Can't get enough VBA?
Subscribe to our free wellsrPRO VBA training program for more VBA tricks. I'll share my top VBA secrets and show you how to import my entire macro library directly into your spreadsheet with just one click.
The VBA macro, GetCursorPosDemo, takes advantage of the user32.dll library and our custom data type, POINTAPI, to return your cursor position in a messagebox. The user32 library can do many things! In addition to returning your cursor coordinates, you can use it to click your mouse and change your cursor position.
Do you want to read more about the user32.dll library? Check out my mouse control article.
All you have to do to get this macro to work is:
- Create a New Module in your VBA Editor
- Paste the Cursor Position Example into your new Module
- Run the Macro GetCursorPosDemo
That’s it! You’re finished! Hai finito! When you run your macro, you’ll get a popup messagebox, like the one below:
Each time you move your mouse and rerun the macro, a new messagebox will report your current cursor location. This is quite handy when you’re, let’s say, trying to program a way to beat an online game in record time. I may or not be speaking from experience. *crickets chirp* Use it, but don’t abuse it!
If you’re trying to map a long series of consecutive mouse movements, here’s a cool suggestion: Modify the above code to copy the following string directly to your clipboard.
"SetCursorPos " & llCoord.Xcoord & ", " & llCoord.Ycoord
Once you get it set up with your clipboard, you can use copy and paste to quickly recreate a series of mouse movements. Leave me a comment if you need help setting this up with your clipboard.
If you like what you see, share this article with a friendand submit a comment below! Subscribe to my email list for more great VBA content.