Reputation:
I want my mouse pointer to move automatically every 30 minutes.
I am writing the code in Excel VBA.
I tried https://support.microsoft.com/en-us/help/152969/visual-basic-procedure-to-get-set-cursor-position but it doesn't work.
Upvotes: 3
Views: 64339
Reputation: 4537
Create new module with following code:
Private dtmNext As Date
Private Type POINTAPI
x As Long
y As Long
End Type
Private Declare PtrSafe Function GetCursorPos Lib "user32" (Point As POINTAPI) As Long
Private Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Integer, ByVal y As Integer) As Long
Sub Move_Cursor()
Dim Hold As POINTAPI
GetCursorPos Hold
SetCursorPos Hold.x + 30, Hold.y
dtmNext = DateAdd("n", 30, Now)
Application.OnTime dtmNext, "Move_Cursor"
End Sub
Sub Stop_Cursor()
Application.OnTime dtmNext, "Move_Cursor", , False
End Sub
Call Move_Cursor()
to start moving the cursor every 30 minuts. To stop the automatic motion, use
Application.OnTime dtmNext, "Move_Cursor", , False
Upvotes: 3
Reputation: 173
Thanks for the first answer, I just made a few updates (PtrSafe
statement) and more friendly names
1-Create a module called "Mouse"
2-This code:
Private Type mousePos
x As Long
y As Long
End Type
Private Declare PtrSafe Function GetCursorPos Lib "user32" (ByRef p As mousePos) As Long
Private Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Integer, ByVal y As Integer) As Long
Private Function mouseGet(ByRef p As mousePos) As Long: GetCursorPos p: End Function
Function mouseSet(x, y As Integer): SetCursorPos IIf(x < 0, 0, x), IIf(y < 0, 0, y): End Function
Function mouseOffset(Optional x As Integer = 0, Optional y As Integer = 0)
Dim Hold As mousePos
mouseGet Hold
mouseSet Hold.x + x, Hold.y + y
End Function
3-Code in another module to test only (Use only mouseSet
and mouseOffset
, if you need mouseGet
just remove the Private
, these are only examples of ways to call it
Sub mouseTest()
Mouse.mouseSet 200, 200
mouseSet 300, 300
Mouse.mouseOffset 200 'y is optional
Mouse.mouseOffset , 200 'x is optional
Mouse.mouseOffset y:=200 'x is optional
mouseOffset 200 'y is optional
mouseOffset 200, 200
End Sub
The reason of the IIf
is because a negative number will set the mouse to the other side of the screem
Upvotes: 1
Reputation: 1
It does work but, you need to create a module. Right click ThisWorksheet-->insert-->Module
.
Only then it works.
Upvotes: -2