MrExcel Publishing
Your One Stop for Excel Tips & Solutions

Mouse control with VBA

Posted by Sam on January 13, 2002 7:00 PM


Is there any way to control the mouse with VBA. What I would like to do is make a tutorial and for example when a button is pushed the mouse will move to a menu on the Excel File Menu and click it to open it, then select one of the choices to demonstrate how to do it.
Any ideas?



Posted by Mike on January 14, 2002 5:48 AM

There is a way to control the mouse but you have to use the WIN32 API to do it. There may be an OCX that would make it easier. What you might consider is using SENDKEYS to send keystrokes to open the menus instead. For example:


would open the File Open Dialog box. Most of the mouse commands have keyboard equivalents. Playing with the WIN32 API to move the mouse around can be very tedious and if you can find another way to accomplish the job I would encourage you to use it instead.

Good luck...Mike

Posted by Jerid on January 14, 2002 6:08 AM

You need to use the Windows32 API, here is an example how to move the cursor. What you would have to do is use this code to move the cursor and then call your click event.

Good Luck


'**Win32 API Declarations
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function SetCursorPos Lib "user32" (ByVal X As Long, ByVal Y As Long) As Long
Private Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long

'**Win32 API User Defined Types
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type

Private Sub test()
Dim Rec As RECT
'Get Left, Right, Top and Bottom of Form1
GetWindowRect GetWindowHandle, Rec
'Set Cursor position on X
SetCursorPos Rec.Right - 600, Rec.Top + 400
End Sub

Private Function GetWindowHandle() As Long


'Gets the Apps window handle, since you can't use App.hInstance in VBA (VB Only)
GetWindowHandle = FindWindow(CLASSNAME_MSExcel, vbNullString)
End Function