-1

I have the following excel vba code and the purpose is when "test.png" appears, the cursor should move to somewhere and left click. The procedure is set to run 10 times and each for 5 sec interval to check "test.png" showing or not.

However, the following code return error. how to rewrite it, any thoughts? many thanks!

'Declare mouse events
Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As LongPtr
Public Declare PtrSafe 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)
Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4
Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
'Declare sleep
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Sub leftclick()
  mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
  Sleep 50
  mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
End Sub

Sub MacroAutoGUI()
img=("C:\Users\lawrence\Desktop\test.png")
for i= 1 to 10
  if img.show =true then
    SetCursorPos 38, 1048
    Call leftclick
    Sleep (5000) 
  end if
next
End Sub
Community
  • 1
  • 1
Yung Lin Ma
  • 121
  • 2
  • 14

1 Answers1

0

You haven't declared the variable img, and I'm not sure how you expect that it will be loaded with an image from this line of code.

img=("C:\Users\lawrence\Desktop\test.png")

Currently your code will be assuming that you wanted a string variable, and that doesn't have a Show method, so I expect your code will be failing at

if img.show =true then

I recommend that you use Option Explicit and Option Strict in all your VBA projects; it will help you avoid these sorts of problems. See here for more information What do Option Strict and Option Explicit do?

DeanOC
  • 7,142
  • 6
  • 42
  • 56