I am trying to automate JavaScript forms/pages in IE7 using VBA. I have already determined that I must use sendkeys to move past a JS alert pop-up. Since this process will take some time to run, the intent of this function is for users to be able to run the process in the background and do other things. This is not my preferred option while working with sendkeys, but I don’t know that I have another choice (other than force users to wait for the process to complete, which I can use as a last resort option).
In order to prevent issues with sendkeys going to the wrong application, I am forcing the focus to the current IE window. In doing so, the focus winds up on the main IE window, and not the alert box. If I try to reset the focus by pausing the codes, then manually clicking on the IE window, the focus does go to the alert box. In other words, it appears setting the focus using code is the culprit.
I have been unsuccessful in finding a way to capture the alert box using my automation, otherwise I would have tried to activate the button control on it.
I am setting the focus using this code:
Private Declare Function SetForegroundWindow Lib "user32" (ByVal HWND As Long) As Long
Sub WaitForIE(myIEWindow As InternetExplorer, HWND As Long, Optional CheckForAlert As Boolean = False)
'OTHER CODE
While myIEWindow.Busy
DoEvents ' Wait until IE is done loading page and/or user actions are done.
Application.Wait DateAdd("s", 1, Now()) ' Wait one second per cycle so as not to use too much CPU
If CheckForAlert Then 'Only check for alert box when certain pages are loaded
Dim IEPage As Variant
Dim PlaceHolder As Long
Dim SearchFor As String
SearchFor = "userMessage = '"
Set IEPage = myIEWindow.Document.Frames(2).Document.Body
PlaceHolder = InStr(IEPage.innerhtml, SearchFor)
If PlaceHolder > 0 Then
If InStr(PlaceHolder + Len(SearchFor), IEPage.innerhtml, "'") > PlaceHolder + Len(SearchFor) + 1 Then ' if userMessage does not equal '' then the alert will show, so clear alert box
SetForegroundWindow HWND 'HWND is the HWND of the myIEWindow
Application.SendKeys "{ENTER}", True
End If
End If
Set IEPage = Nothing
End If
Wend
' MORE CODE
End Sub
Is there an alternative to this method (setting focus), or is there another step to this method I am missing?
The trick is to send a {TAB} before sending your {ENTER}, this will bring focus to the alert box
should work.