Search code examples
vbabotsscraper

Web Scraper won't fill in a child window that my VBA code launches


I have the following code in VBA which opens up an IE page, fills it in and then clicks on a button that opens up a new IE window. However, my code is not able to fill in the first dropdown of the new window. Any help would be greatly appreciated.

Sub Van()
    Dim IE As Object
    Dim IE2 As Object

    Set IE = CreateObject("InternetExplorer.Application")
    'Set IE2 = CreateObject("InternetExplorer.Application")

    IE.navigate ("website")
    IE.Visible = True

    Do
        DoEvents
    Loop Until IE.readyState = 4

    Set d = IE.document

    'Code now clicks on buttons or dropdowns etc
    Application.Wait (Now + TimeValue("00:00:03"))

    Set IE2 = GetIE("pop-up page")

    WaitFor IE2

    'Tried this too
    'Application.Wait (Now + TimeValue("00:00:05"))
    IE2.document.getElementsByTagName("select")(0).Value = "X"

    'Also tried the line below
    'IE2.document.GetElementsbyname("name")(0).SelectedIndex = 1

End Sub

Function GetIE(sAddress As String) As Object

    Dim objShell As Object, objShellWindows As Object, o As Object
    Dim retVal As Object, sURL As String

    Set retVal = Nothing
    Set objShell = CreateObject("Shell.Application")
    Set objShellWindows = objShell.Windows

    'see if IE is already open
    For Each o In objShellWindows
        sURL = ""
        On Error Resume Next
        sURL = o.LocationURL
        On Error GoTo 0
        If sURL <> "" Then
            'MsgBox sURL
            If sURL = sAddress Then
                Set retVal = o
                Exit For
            End If
        End If
    Next o

    Set GetIE = retVal
End Function

Sub WaitFor(IE)
    Do
        DoEvents
    Loop Until IE.readyState = 4
End Sub

Solution

  • The page in the pop-up may not be fully loaded when you're trying to access the select - try adding a wait loop until loading is done. I like to pull out the "wait" loop into a re-usable function:

    Set IE2 = GetIE("https://secure.apia.com.au/NASApp/apia/CRQuoteServlet?" & _
                    "pageAction=openModelSelectionWindow&currentSequenceNumber=")
    
    WaitFor IE2
    
    IE2.document.getElementsByTagName("select")(0).Value = "JAY"
    

    WaitFor:

    Sub WaitFor(IE)
        Do
            DoEvents
        Loop Until IE.readystate = 4
    End sub