Você está na página 1de 7

01/11/2016 Move and Click your Mouse with a VBA Macro ­ wellsr.

com

Move and Click your Mouse with a VBA Macro
The VBA Tutorials Blog
(/vba/)

May 15, 2015   Looking for More Excel Tutorials (/vba/excel/)?   

Quick Jump
Introduction | Example | Tutorial | Applications | Comments 

Introduction ­ Mouse Control
Did you know you could control your mouse with a VBA macro? Among other things, the user32 library (user32.dll) allows you to right­click, left­click and change your
cursor position. Keep reading to find out how you can use mouse controls to create hands­free MS Paint art.

This article teaches you how to programmatically control your mouse with VBA. Instead of controlling your mouse manually, would you like to record your mouse and have
it instantly converted to a VBA macro? I made an Excel add­in for that. Check out Mouse to Macro (/vba/2015/excel/Mouse­To­Macro­Excel­Add­in/) ­ it’ll save you hours
of programming!

Example
Create MS Paint Art with Mouse Control Macro
'Declare mouse events 
Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long 
Public Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long) 
Public Const MOUSEEVENTF_LEFTDOWN = &H2 
Public Const MOUSEEVENTF_LEFTUP = &H4 
Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8 
Public Const MOUSEEVENTF_RIGHTUP As Long = &H10 
'Declare sleep 
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 
 
Sub CityscapeSkyline() 
15
'Open MS Paint and select Natural pencil Brush with 6px width 
Shares
For k = 1 To 3 
  SetCursorPos 16, 500 
  Sleep 50 
15
  mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0 
  For i = 16 To 600 Step 5 
    For j = 500 To 300 Step ‐Int((180 ‐ 10 + 1) * Rnd + 10) 
      SetCursorPos i, j 
      Sleep 10 
    Next j 
  Next i 
  mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0 
Next k 
End Sub

Your time is valuable. It's time to become a VBA expert.

Enter your email address

Subscribe to wellsr.com

Tutorial
How to automatically create your own skyline art

http://wellsr.com/vba/2015/excel/vba­mouse­move­and­mouse­click­macro/ 1/7
01/11/2016 Move and Click your Mouse with a VBA Macro ­ wellsr.com

How to automatically create your own skyline art
Want to create a city skyline? Follow these steps to create your own art:

1. Open your Excel VBA Editor (/vba/excel/open­visual­basic­editor/)
2. Open MS Paint
3. Place your VBA editor on the right side of your screen and your MS Paint window on the left, like so:

×
It's time to become a VBA expert

Join my popular newsletter, where I share my best VBA tips and tutorials to show you how to finally become the VBA Expert you've always wanted to
be.  

Start mastering VBA and receive my powerful FREE Excel Add­in when you subscribe.
4. Create a New Module (/vba/excel/creating­a­macro/#Module) in your VBA Editor
5. Paste the Mouse Control Example (/vba/2015/excel/vba­mouse­move­and­mouse­click­macro/#Example) into your new Module
Enter your email address
6. Select the Natural pencil brush in MS Paint

Sign up Now!

Powered by SumoMe (https://sumome.com/?src=sm­sb­f985555dd1426b853b0119b4da00077bbc3b4ff33f537ee31b73e8344ed6c4e7)

7. Change your brush width to 6px

15
Shares

15

8. Execute the CityscapeSkyline Macro, sit back, and watch your automatic artist to its work!

Here’s the skyline art that was created when I ran my macro.

http://wellsr.com/vba/2015/excel/vba­mouse­move­and­mouse­click­macro/ 2/7
01/11/2016 Move and Click your Mouse with a VBA Macro ­ wellsr.com

MS Paint Skyline Art with VBA Macro

Looks like a big city, eh? The beauty of this macro is that the heights of the buildings are random. The Step declaration  Step ‐Int((180 ‐ 10 + 1) * Rnd + 10) ×
It's time to become a VBA expert
randomly moves the mouse position up from 10 pixels to 180 pixels until it’s less than 300 pixels from the top of your screen. Each time you run the macro, your skyline
will be different.
Join my popular newsletter, where I share my best VBA tips and tutorials to show you how to finally become the VBA Expert you've always wanted to
be.  
Practical VBA Mouse Control
Sure, that was pretty cool and all but it wasn’t very practical, was it? Here, I’ll try to explain how to move your mouse, left­click and right­click. I’ll also present some best
Start mastering VBA and receive my powerful FREE Excel Add­in when you subscribe.
practices regarding the Sleep function. Remember to paste the following code at the top of your module before trying these examples:
Enter your email address

'Declare mouse events 
Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long 
Sign up Now!
Public Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long) 
Public Const MOUSEEVENTF_LEFTDOWN = &H2 
Powered by SumoMe (https://sumome.com/?src=sm­sb­f985555dd1426b853b0119b4da00077bbc3b4ff33f537ee31b73e8344ed6c4e7)
Public Const MOUSEEVENTF_LEFTUP = &H4 
Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8 
Public Const MOUSEEVENTF_RIGHTUP As Long = &H10 
'Declare sleep 
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Move your Mouse
The  SetCursorPos  line positions your mouse cursor relative to the top left of your screen (position 0, 0). For example,  SetCursorPos 25, 100  moves your mouse 25
pixels from the left of your screen and 100 pixels down from the top of your screen.

Left­click
15
The left­click down and left­click up buttons are independent. This gives you the ability to “hold” your mouse down while you move it around, like you would to highlight text.
Shares

However, if you want to left­click without the hold, paste the following subroutine into your VBA editor and call it (  Call LeftClick  ) from a different subroutine:


15

Private Sub LeftClick() 
  mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0 
  Sleep 50 
  mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0 
End Sub

What if you need to double­click? Just call the macro twice!

Right­click
Like the left­click, the right mouse down and mouse up clicks are independent. Here’s a sample of a routine right­click event:

Private Sub RightClick()
  mouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0 
  Sleep 50 
  mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0 
End Sub

64­Bit Mouse Control

http://wellsr.com/vba/2015/excel/vba­mouse­move­and­mouse­click­macro/ 3/7
01/11/2016 Move and Click your Mouse with a VBA Macro ­ wellsr.com

To control your mouse on a 64­bit machine, modify the two Public Declare statements as follows:

Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As LongPtr 
Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As

Importance of Sleep
The  Sleep  line delays your code for the number of milliseconds you declare. For example,  Sleep 5000  will pause your code for 5 seconds.

Without the Sleep command, your computer may not register your mouse clicks or mouse movements. In other words, Sleep makes your mouse control macros more
reliable.

Application Ideas
It’s a good idea to make sure your window will be placed in the same spot before running mouse control macros. One way to do this is to use vba to maximize your
×
It's time to become a VBA expert
window (/vba/2016/excel/vba­maximize­window­in­left­monitor/).

Join my popular newsletter, where I share my best VBA tips and tutorials to show you how to finally become the VBA Expert you've always wanted to
Want to earn a high score on that computer game you like so much? Automate it! Whether you like it or not, I’ve used mouse control to set records on several flash­based
be.  
web games. Hey, it’s funner to write a VBA code to play the game than it is to actually play some of those games!

Start mastering VBA and receive my powerful FREE Excel Add­in when you subscribe.
I also use mouse controls to automate many of my routine tasks at my nuclear engineering job. A while back, I wrote a macro to open and fill out my timesheet. I just press
a button and watch my computer do my work. If you need help automating your routine tasks at work, let me know and I’ll be happy to help! I’m all about increasing
Enter your email address
efficiency.

Sign up Now!
If you’re looking to develop your fundamentals, practice drawing basic geometric shapes in Paint. I started learning VBA mouse controls by painting squares.

Powered by SumoMe (https://sumome.com/?src=sm­sb­f985555dd1426b853b0119b4da00077bbc3b4ff33f537ee31b73e8344ed6c4e7)

Comments
If you like what you see, subscribe to my email list (http://eepurl.com/bWu2A­/), share this article with a friend, submit a comment below and follow me on Google+
(https://plus.google.com/+RyanWells)! Come back often to see more great VBA ideas.

Remember, if you or your company are struggling with VBA, just contact me (/#Contact) and I’ll gladly point you in the right direction.

Discover how this Nuclear Engineer Mastered Excel VBA
15 And why you should, too
Shares

Your time is valuable. It's time to become a VBA expert.
15
Enter your email address

Subscribe to wellsr.com

About Ryan Wells

http://wellsr.com/vba/2015/excel/vba­mouse­move­and­mouse­click­macro/ 4/7
01/11/2016 Move and Click your Mouse with a VBA Macro ­ wellsr.com

Ryan Wells (https://plus.google.com/+RyanWells) is a Nuclear Engineer and professional VBA Developer. He is the lead developer of several VBA applications, including
CF Shapes (https://gum.co/CFsingle) ­ the premier Excel Add­in for enabling conditional formatting for shapes. Discover more of his popular Excel Add­ins, like Mouse To
Macro (https://gum.co/M2Mfull), at his dedicated Excel Add­ins (/vba/add­ins/) page.

Seguir 287 Follow 79 followers


     

11 Comments wellsr.com VBA Tutorials 
1 Login

  Recommend  1 ⤤ Share Sort by Best

Join the discussion…

Sasha Bouchard • 4 months ago
Hi Ryan, Goal here is to Shift­F2 to replicate a double_left­click. ×
It's time to become a VBA expert
What are your thoughts on recording the position of the last activecell? ­ IMO this is coded easily using getCursorPos and SetCursorPos. However, can this be
possible by taking in account window resizing with the window_resize Event? What about recording window movement, and on_screen scrolling? I guess zoom
Join my popular newsletter, where I share my best VBA tips and tutorials to show you how to finally become the VBA Expert you've always wanted to
factoring as well, although it is common for it to remain to 100%.
be.   △   ▽ • Reply • Share ›

Noel Raquid • 4 months ago
Start mastering VBA and receive my powerful FREE Excel Add­in when you subscribe.
How can I set the position of the mouse relative to the active window, not at an absolute position on the screen? 
Thank you in advance.
Enter your email address
△   ▽ • Reply • Share ›

wellsr  Mod   > Noel Raquid  •  4 months ago Sign up Now!


Hi, Noel! Will you be moving your mouse around an Excel window or will it be a different window? The reason I'm asking is because things get a bit more
Powered by SumoMe (https://sumome.com/?src=sm­sb­f985555dd1426b853b0119b4da00077bbc3b4ff33f537ee31b73e8344ed6c4e7)
complicated when querying non­Excel window positions
△   ▽ • Reply • Share ›

Noel Raquid > wellsr • 4 months ago
I will be moving from an Excel window to a non­Excel window, such as a web browser.
△   ▽ • Reply • Share ›

wellsr  Mod   > Noel Raquid  •  4 months ago

It's not the desired way, but one way to do this is to make sure your window takes up your entire screen, so the mouse position relative to
the active window is the same as the absolute position relative to your screen.

This article demonstrates how to maximize your window (in the upper left monitor, if on a dual monitor system):
http://wellsr.com/vba/2016/exc...
15
Shares △   ▽ • Reply • Share ›

Thinus Bothma • 8 months ago
15 Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Give and error, please assist
△   ▽ • Reply • Share ›

wellsr  Mod   > Thinus Bothma  •  8 months ago

Hi, Thinus. To run this code on a 64­bit platform, place "PtrSafe" before before all the 32­bit functions. For example, change:

"Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long 
Public Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal
dwExtraInfo As Long)
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)"

to

"Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long 
Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal
dwExtraInfo As Long)
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)"
△   ▽ • Reply • Share ›

Ram S > wellsr • 11 days ago

http://wellsr.com/vba/2015/excel/vba­mouse­move­and­mouse­click­macro/ 5/7
01/11/2016 Move and Click your Mouse with a VBA Macro ­ wellsr.com

Hi,
I am using plain VBScript. Am able to get to the point of positioning the cursor, & have declared my variables as follows on my 64­bit laptop:

' Dim MOUSEEVENTF_LEFTDOWN, MOUSEEVENT_LEFTUP

Private Const MOUSEEVENTF_LEFTDOWN = &H2
Private Const MOUSEEVENTF_LEFTUP = &H4

Private Const VK_CONTROL = &H11 
Private Const VK_F1 = &H70

& ....

later ...

Following are my Vbscript ­ for mouse move to location & to actually do the click on a button.

Excel.ExecuteExcel4Macro("CALL(""user32"",""SendInput"",""&H2""," & 0 & "," & 0 & "," & 0 & "," & 0 & ")") 'cursor will go down (like click)
wscript.sleep 1000
Excel.ExecuteExcel4Macro("CALL(""user32"",""SendInput"",""&H4""," & 0 & "," & 0 & "," & 0 & "," & 0 & ")") 'cursor will go down (like click)
×
It's time to become a VBA expert see more

△   ▽ • Reply • Share ›
Join my popular newsletter, where I share my best VBA tips and tutorials to show you how to finally become the VBA Expert you've always wanted to
be.   alt • 9 months ago
Hello

Start mastering VBA and receive my powerful FREE Excel Add­in when you subscribe.
I've tried with sleep 1000, and the result is the same.
Seems like when moving cursor, left button is not pressed.
△   ▽ • Reply • Share ›
Enter your email address

alt • 9 months ago
Sign up Now!
Hello Mr. Wells

Powered by SumoMe (https://sumome.com/?src=sm­sb­f985555dd1426b853b0119b4da00077bbc3b4ff33f537ee31b73e8344ed6c4e7)
I've tried your code. It is very useful, but I found some issues. When I try the paint example, i didn't get the picture. The problem I have is that the left mouse
button is not always pressed. It seems that the button is only pressed when the MOUSEEVENTF_LEFTDOWN is executed, and release while moving.

Googling a little bit, I found this quote:

"The flag bits that specify mouse button status are set to indicate changes in status, not ongoing conditions. For example, if the left mouse button is pressed and
held down, MOUSEEVENTF_LEFTDOWN is set when the left button is first pressed, but not for subsequent motions. Similarly, MOUSEEVENTF_LEFTUP is set
only when the button is first released."

Can you help me?
△   ▽ • Reply • Share ›

wellsr  Mod   > alt •  9 months ago

Hi, Alt! What happens when you try larger numbers after the sleep command? Try doubling them. Sometimes the mouse begins to move too fast and the
15 mouse down event doesn't register.
Shares
△   ▽ • Reply • Share ›

15
ALSO ON WELLSR.COM VBA TUTORIALS

Draw Lines or Arrows Between Cells with VBA VBA Copy to Clipboard, Paste and Clear
2 comments • a year ago• 3 comments • a year ago•
Erwin Segura — Thanks! Using in Trellis diagram! wellsr — No problem ­ I'm glad it wound up working well!

Create an Awesome Excel Splash Screen For Your Spreadsheet Mouse To Macro Excel Add­in
24 comments • 8 months ago• 8 comments • a year ago•
wellsr — That's a brilliant idea about adding to­do list items to your wellsr — I appreciate the kind words, Lauren:) I really hope you enjoy the
spreadsheet! I can see querying Outlook tasks that are coming … add­in! I try to create new content regularly, so I …

✉ Subscribe d Add Disqus to your site Add Disqus Add 🔒 Privacy

http://wellsr.com/vba/2015/excel/vba­mouse­move­and­mouse­click­macro/ 6/7
01/11/2016 Move and Click your Mouse with a VBA Macro ­ wellsr.com

Sign up for my Mastering
VBA Newsletter

(http://eepurl.com/bWxXIH) 
And get the power of wellsr.com
right in Excel with a FREE copy of ×
It's time to become a VBA expert
my Excel Add­In. 
 
email address
Join my popular newsletter, where I share my best VBA tips and tutorials to show you how to finally become the VBA Expert you've always wanted to
be.   Sign up Now!

Start mastering VBA and receive my powerful FREE Excel Add­in when you subscribe.

Enter your email address
 (https://gum.co/M2Mfull)

Sign up Now!

Powered by SumoMe (https://sumome.com/?src=sm­sb­f985555dd1426b853b0119b4da00077bbc3b4ff33f537ee31b73e8344ed6c4e7)

15
Connect
Shares

15

  (http://eepurl.com/bWu2A­/) 

(https://plus.google.com/+RyanWells) 

(https://twitter.com/ryanwellsr) 
(https://www.linkedin.com/in/ryanwellsr)

http://wellsr.com/vba/2015/excel/vba­mouse­move­and­mouse­click­macro/ 7/7

Você também pode gostar