How to get position of mouse via VB in a worksheet



I would like to monitor the position of the mouse in a worksheet and react to

So when the mouse moves an event triggered which reports the x,y position
and if possible the cell under the current location of the mouse. If the x,y
position is recorded I would need to know the x,y limits of the worksheet and
the view limit of the cells on the screen.

I would be grateful for any help given.

Gary''s Student

Here is some really simple code to sample or set the mouse position:

Declare Function GetCursorPos Lib "user32" _
(lpPoint As POINTAPI) As Long

x As Long
y As Long
End Type

Declare Function SetCursorPos Lib "user32" ( _
ByVal x As Long, _
ByVal y As Long _
) As Long
Sub ShowPos()
Dim lRetVal As Long
lRetVal = GetCursorPos(Pos)
MsgBox Pos.x & ", " & Pos.y
End Sub

Sub SetPos()
Dim retv As Long
retv = SetCursorPos(67, 139)
End Sub

Peter T

As Gary's Student has shown it is relatively easy to get the screen position
of the mouse. However relating that to what cell it is over is rather more

Chip Pearson shows one way here,

FWIW I use a completely different way

The next task, for your needs, is to use a Timer method to poll the mouse
position periodically (say every 0.1 sec), work out if the mouse which cell
the mouse is come to a stop over and go from there.

Whether using Chip's approach to relate cells to screen coordinates, or some
other equivalent method, combining with the timer then doing whatever is the
objective is not trivial. However something like positioning and showing a
cell tooltip is doable.

Peter T

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question