Monday, December 29, 2025

Single left click in VBA - Excel

 


    Private Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long

    Private 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)



' Define the mouse events

Public Const MOUSEEVENTF_LEFTDOWN = &H2

Public Const MOUSEEVENTF_LEFTUP = &H4

Public Const MOUSEEVENTF_ABSOLUTE = &H8000

Public Const MOUSEEVENTF_MOVE = &H1


Sub SimulateLeftClick(ByVal x As Long, ByVal y As Long)

    ' Move the cursor to the specified coordinates (screen coordinates)

    SetCursorPos x, y

    

    ' Perform the left click (Down and then Up)

    mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0

    mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0

End Sub


Sub TestClick()

    ' Clicks at screen coordinates X=50, Y=50

    Call SimulateLeftClick(40, 200)

End Sub


No comments:

Post a Comment