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
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 friend, submit a comment below and follow me on Google+! Subscribe to my email list for more great VBA content.
Get these macros delivered right to your spreadsheet for free
Access tutorials and import my macros without ever leaving ExcelShow me - It's free
About Ryan Wells
Ryan Wells is a Nuclear Engineer and professional VBA Developer. He is the lead developer of several VBA applications, including PDF VBA - a leading Excel Add-in for exporting Excel Objects, like charts and tables, to PDFs. Discover more of his popular Excel Add-ins, including Mouse To Macro and CF Shapes, at his dedicated Excel Add-ins page.Follow