I have a simple script that hunts for popup boxes that are generated for website and Excel. It works most of the time but errors out occasionlly and seemingly randomly. The error is line: 6 Char: 3 Error: Invalid window handle Code: 80070578
I can't figuer out why it'll work for hours then error seemingly at random. Also the script uses a lot of CPU if anyone could advise how to make it more efficent. Thanks For your time
Set WshShell = CreateObject("WScript.Shell")
Do
Do
ret = WshShell.AppActivate("Message from webpage")
ret2 = WshShell.AppActivate("Microsoft Excel")
Loop Until ret = True or ret2 = True
WScript.sleep 500
ret = WshShell.AppActivate("Message from webpage")
ret2 = WshShell.AppActivate("Microsoft Excel")
If ret = True or ret2 = True Then
WScript.Sleep 200
WshShell.SendKeys("{ENTER}")
End If
WScript.sleep 500
Loop
The simple answer is VBScript is not designed to run scripts continuously.
As for what you can do the improve it, let's dissect it a little.
The outer loop is running every 500 milliseconds, which means that every half a second the script is triggered forever this is heavy for what it is doing and will likely cause heavy CPU usage the longer it runs.
Does the outer loop need to run so often, could you not increase the
Sleep()from 500 to say 1000 or even 5000 to reduce the load on the CPU?Better yet you could drop the outer loop completely and run the task using Windows own Task Scheduler which will allow you to create a scheduled task that will execute the script however often you wish. That way the script runs to completion closes releases the memory and is then run again at the next interval.