getElementById上出现“需要对象”错误

时间:2019-12-23 21:14:17

标签: excel vba getelementbyid

当我尝试getElementById时,会引发运行时错误424。

基本上,我的代码将打开并登录到网页,然后单击按钮导航到新屏幕。加载此新屏幕后,我们尝试单击上述引发错误的按钮。

Sub Website()

    Dim ie_Obj As InternetExplorer

    Set ie_Obj = New InternetExplorer
    ie_Obj.Visible = True

    ie_Obj.navigate "https://www.websitehere.omitted/"
    Do While ie_Obj.Busy = True Or ie_Obj.readyState <> 4: DoEvents: Loop

    ie_Obj.Document.getElementById("LoginBtn").Click ' This one works fine.  What's wrong with the next one?
    Do While ie_Obj.Busy = True Or ie_Obj.readyState <> 4: DoEvents: Loop

    Application.Wait (Now + TimeValue("0:00:05")) ' I added this to allow the page to load.

    ie_Obj.Document.getElementById("chkAllrlbLocs").Click' <--- Code breaks here

    '... more code follows

我知道原因之一可能是因为该页面尚未完成加载。但是,如果我逐行使用F8并允许其加载,它仍然会引发错误。

这是我的HTML:

<input name="chkAllrlbLocs" tabindex="-1" id="chkAllrlbLocs" onclick="if (! SelectAllLBItems('rlbLocs')) return false;setTimeout('__doPostBack(\'chkAllrlbLocs\',\'\')', 0)" type="checkbox">

1 个答案:

答案 0 :(得分:0)

“ chkAllrlbLocs”不是ID,是一个名称。但是“名称”只是一个属性。所以试试这个: (如果该方法无效,则应发布该网址)

    Sub Website()

    Dim ie_Obj As InternetExplorer
    Dim inputTags As Object

    Set ie_Obj = New InternetExplorer
    ie_Obj.Visible = True

    ie_Obj.navigate "https://www.websitehere.omitted/"
    Do While ie_Obj.Busy = True Or ie_Obj.readyState <> 4: DoEvents: Loop

    ie_Obj.Document.getElementById("LoginBtn").Click ' This one works fine.  What's wrong with the next one?
    'The following line doesn't work because "ie_Obj.Busy = True Or ie_Obj.readyState <> 4: DoEvents" is
    'already at "ready" . You are saved by the following line after this: "Application.Wait ..."
    'So I commented it out
    'Do While ie_Obj.Busy = True Or ie_Obj.readyState <> 4: DoEvents: Loop
    Application.Wait (Now + TimeValue("0:00:05")) ' I added this to allow the page to load.

    'This is the "try this" part
    'But I think you must think a little by yourself
    For Each inputTags In ie_Obj.Document.getElementsByTagName("input")
      If inputTags.getAttribute("name") = "chkAllrlbLocs" Then
        'Think about the following comment line
        'Code when the right input field was be found
        Exit For
      End If
    Next inputTags

    '... more code follows
End Sub