1

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
3
  • What error message are you getting when fails and on which line? Commented Dec 16, 2018 at 6:58
  • 1
    Hi QHarr, thanks for your prompt support. I received no error message from the vba. The IE just seems stop at HTMLButton.Click and the second part of code takes no effects. Commented Dec 16, 2018 at 7:00
  • See initial suggestions below. Commented Dec 16, 2018 at 7:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.