【问题标题】:Code works during F8 step through, but not when run normally代码在 F8 单步执行期间有效,但在正常运行时无效
【发布时间】:2017-11-09 01:59:22
【问题描述】:
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

代码在我逐行执行时有效,但在正常运行时无效。我尝试在某些部分插入长达 45 秒的休息时间,但没有成功。

正常运行,在ie.document.getElementById("logo").Click期间代码中断并给我一个

'424'对象需要错误

【问题讨论】:

  • 那么当你正常运行的时候,有没有出现什么情况?
  • 加载雅虎搜索后出现“424”对象所需的运行时错误
  • 考虑使用更好的 API:stackoverflow.com/a/17481643/1188513
  • 感谢您的建议。我对此并不熟悉,但它似乎要快得多。我得去看看!

标签: html vba excel internet-explorer


【解决方案1】:

因为这是对象尚不可用的问题,解决问题的最简单方法是首先将logo设置为对象-循环直到它为Not Nothing,然后点击它。

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

所以你实际上是在替换这一行:
ie.document.getElementById("logo").Click

用这个:

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

即使在readyState = Complete 之后,在某些情况下对象也没有完全初始化。这可能部分是由于除了您看到的主 HTML 页面之外,还有多个 iFrame 做自己的事情。

【讨论】:

    【解决方案2】:

    我同意 K.Davis 的观点,就绪状态并不总是可靠的。 试试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多