Introduction | Example | Tutorial | Applications
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.
Example
Get Mouse Position
#If VBA7 Then
Declare PtrSafe Function GetCursorPos Lib "user32" Alias "GetCursorPos" (lpPoint As POINTAPI) As Long
#Else
Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
#End If
' 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
Make powerful macros with our free VBA Developer Kit Tutorials like this can be complicated. That’s why we created our free VBA Developer Kit and our Big Book of Excel VBA Macros to supplement this tutorial. Grab them below and you’ll be writing powerful macros in no time.
Tutorial
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!
Application Ideas
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.
That’s all for this tutorial. When you’re ready to take your VBA to the next level, subscribe using the form below.