选择使用IE对象

时间:2015-05-13 18:43:33

标签: excel vba internet-explorer excel-vba

在VBA中为下拉列表选择以下代码。

当我运行这个时,我得到粗线上的错误,说“运行时错误91 - 对象变量或没有设置块变量”..新到VBA ......

Sub NACDP()
' open IE, navigate to the desired page and loop until fully loaded
    Set ie = CreateObject("InternetExplorer.Application")
    my_url = "https://cdeployna.cognizant.com/"

    With ie
        .Visible = True
        .Navigate my_url
        .Top = 50
        .Left = 530
        .Height = 400
        .Width = 400

    Do Until Not ie.Busy And ie.readyState = 4
        DoEvents
    Loop

    End With

' Input the userid and password
    ie.Document.getElementById("loginControl_UserName").Value = ""
    ie.Document.getElementById("loginControl_Password").Value = ""

' Click the "Login" button
    ie.Document.getElementById("loginControl_LoginButton").Click

    Do Until Not ie.Busy And ie.readyState = 4
        DoEvents
    Loop

    ie.Document.getElementById("ctl00_ddlRoles").selectedindex = 1
    ie.Document.getElementById("ctl00_ddlRoles").FireEvent ("onchange")

     Do Until Not ie.Busy And ie.readyState = 4
        DoEvents
    Loop

    ie.Document.getElementById("ctl00_ContentBody_searchCDPList_ddlFieldName").selectedindex = 1
    ie.Document.getElementById("ctl00_ContentBody_searchCDPList_ddlFieldName").FireEvent ("onchange")
    ie.Document.getElementById("ctl00_ContentBody_searchCDPList_txtValue").Value = "Java"

    ' Click the "Search" button

    ie.Document.getElementById("ctl00_ContentBody_searchCDPList_btnSearch").Click


End Sub

1 个答案:

答案 0 :(得分:1)

似乎“Do Until Not ie.Busy and ie.readyState = 4”循环并没有真正做到它应该做的事情。收到错误后,如果按Debug然后继续代码,它将成功完成。所以,正在发生的事情是,当行首次执行时,您正在搜索的元素仍然不存在。您可以在问题行之前使用以下内容修补此问题:

Do While ie.Document.getElementById("ctl00_ContentBody_searchCDPList_ddlFieldName") Is Nothing
    DoEvents
Loop

这将循环直到找到元素,然后代码继续成功。