Ken
Ken

Reputation: 19

Using VBA to navigate a href in IE HTML document

I am trying to use VBA to navigate IE to search some of the information for me. However, after the code is written and I run it. I found everything is fine before the part of clicking href, but if I use "F8" to execute the code one by one and it works. Unfortunately, I haven't found some situation like mine in this forum. Can someone give some hints to me? Thanks

Sub GetData()
    Dim IE As New SHDocVw.InternetExplorer
    Dim HTMLDoc As MSHTML.HTMLDocument
    Dim HTMLInput As MSHTML.IHTMLElement
    Dim HTMLButton As MSHTML.IHTMLElement
    Dim HTMLAllhref As MSHTML.IHTMLElementCollection

    studentid = 12345678

    Set IE = New InternetExplorerMedium
    IE.Visible = True
    IE.Navigate "https://xxx.xxx"

    Do While IE.ReadyState <> READYSTATE_COMPLETE
    Loop

    Set HTMLDoc = IE.Document
    Set HTMLInput = HTMLDoc.getElementById("abcd")
    HTMLInput.Focus
    HTMLInput.FireEvent("onchange")
    HTMLInput.Value = studentid

    Set HTMLButton = HTMLDoc.getElementById("submit")
    HTMLButton.Click

The part above works properly, but the following part works only if I use "F8" to execute one by one

    Set HTMLAllhref = HTMLDoc.GetElementsByTagName ("a")
    For Each link in HTMLAllhref
        If InStr(link.innerText, studentid) Then
            IE.Navigate link.href
            Exit For
        End If
    Next
End Sub

Upvotes: 1

Views: 583

Answers (1)

QHarr
QHarr

Reputation: 84475

1) If works with F8 it is usually a timing issue and you need to determine where a wait needs to happen.

As a minimum be sure to use a proper wait after each .Navigate2, .Click and .Submit to allow for page loading:

While IE.Busy Or ie.readyState < 4: DoEvents: Wend

Potentially also after:

HTMLInput.FireEvent("onchange")

2) The recommended method is .navigate2, not .navigate.

Upvotes: 1

Related Questions