1
Sub InternetPractice()

    Dim ie As InternetExplorer

    Set ie = New InternetExplorer

    ie.Visible = True

    ie.navigate "https://www.yahoo.com"

    Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop

    ie.document.getElementById("uh-search-box").Value = "Earth"
    ie.document.getElementById("uh-search-button").Click

    Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop

    ie.document.getElementById("logo").Click

    Set ie = Nothing

End Sub

The code works when I step through it line by line, but not when run normally. I have tried inserting up to 45 second breaks in certain parts with no success.

Running normally, the code breaks during ie.document.getElementById("logo").Click and gives me a

'424' object required error

braX
  • 11,506
  • 5
  • 20
  • 33
T Doe
  • 81
  • 9

2 Answers2

2

Because this is an issue where the object is not yet available, the easiest way to fix your problem is to set logo as an object first - looping until it is Not Nothing, then click it.

Option Explicit

Sub InternetPractice()

    Dim ie As New InternetExplorer, logoBtn As Object

    With ie
        .Visible = True
        .navigate "https://www.yahoo.com"
        Do While .Busy Or .readyState <> 4: DoEvents: Loop
        .document.getElementById("uh-search-box").Value = "Earth"
        .document.getElementById("uh-search-button").Click
        Do While .Busy = True Or .readyState <> 4: DoEvents: Loop
        On Error Resume Next
        Do While logoBtn Is Nothing
            Set logoBtn = .document.getElementById("logo")
            DoEvents
        Loop
        On Error Goto 0
    End With
    logoBtn.Click

End Sub

So you are essentially replacing this line:
ie.document.getElementById("logo").Click

with this:

    Dim logoBtn As Object
    Do While logoBtn Is Nothing
        Set logoBtn = ie.document.getElementById("logo")
        DoEvents
    Loop
    logoBtn.Click

Even after readyState = Complete, in some cases objects are not fully initialized. This can be due in part to having multiple iFrames that do their own thing apart from the main HTML page you see.

K.Dᴀᴠɪs
  • 9,945
  • 11
  • 33
  • 43
1

I agree with K.Davis, the Ready State is not always reliable. Try this:

Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop
Sleep(100)
Do While ie.Busy = True Or ie.readyState <> 4: DoEvents: Loop