1

I am trying to attach a hammer image onto the mouse cursor on Excel. It works fine without the Do Loop, that is it moves the image close to the mouse cursor when I run the macro using a button on sheet1. The problem starts when I try to make the image follow the cursor on-the-fly, using a Do Loop. In the past, I was able to make that happen without any errors, but I did not save that Excel workbook. Now, I am trying to do it again and it crashes Excel every time. I might get lucky and get a "Left method of object failed" or a "Top method of object failed" error, but that does not really help. Here is the VBA code:

Option Explicit

Declare PtrSafe Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Type POINTAPI
    x As Long
    y As Long
End Type

Sub MoveHammer()

    Dim lngStatus As Long
    Dim typWhere As POINTAPI
    Dim activate As Boolean
    activate = True

    Do While activate = True
    lngStatus = GetCursorPos(typWhere)

    Sheet1.Shapes("hammer").Left = 0.75 * (typWhere.x - 77)
    Sheet1.Shapes("hammer").Top = 0.75 * (typWhere.y - 274)
    Loop
End Sub

"hammer" is the name of the picture object that I have inserted. Thanks.

4
  • 2
    Why are you trying to kludge this yourself instead of just using SetCursor(). You seem to be aware of the WinAPI, because you're using it for GetCursorPos(). Commented May 21, 2018 at 12:32
  • @JohnColeman OMG YES! How can I be so blind and naive? Of course I would need a DoEvents statement. Thank you so much! Type this as a response so I can mark it. Commented May 21, 2018 at 13:00
  • @KenWhite the reason is because I do not want to set the cursor to a certain position. I simply want to have that image follow the cursor. So I am grabbing the position of the cursor with GetCursorPos(). Commented May 21, 2018 at 13:02
  • I didn't say SetCursorPos(). I mentioned SetCursor(). They don't do the same things. :-) Commented May 21, 2018 at 16:37

1 Answer 1

1

Since VBA lacks multithreading, in order to get responsiveness while inside of the loop you will need a DoEvents inside of the body of the loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.