VBA代码,用于根据Excel工作簿中的值从Web表单下拉列表中选择值

nbysray5  于 2023-03-04  发布在  其他
关注(0)|答案(1)|浏览(128)

我需要从一个web表单下拉列表中选择一个值,这个值是基于我正在编写宏的excel手册中的值,到目前为止,我已经能够导航到网站,并使用下面的vba代码单击所需的选项卡:

Sub FillInternetForm()
    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")

    ie.Navigate "website I'm navigating to"
    ie.Visible = True
    While ie.Busy
        DoEvents 'wait until IE is done loading page.
    Wend

    Set AllHyperLinks = ie.Document.getElementsByTagName("A")
    For Each Hyper_link In AllHyperLinks
        If Hyper_link.innerText = "Reconciliations" Then
            Hyper_link.Click
            Exit For
        End If
    Next
End Sub

接下来,我需要根据我正在尝试编写宏的工作簿中的预定义值(单元格引用)单击“Preparer”、“Approver”或“Reviewer”。下面是HTML代码,我相信我需要在宏中引用这些代码来执行所描述的操作:

<td class="DashControlTableCellRight"><select name="ctl00$MainContent$ucDashboardPreparer$ucDashboardSettings$ctl00$ddlRoles" class="ControlDropDown" id="ctl00_MainContent_ucDashboardPreparer_ucDashboardSettings_ctl00_ddlRoles" onchange="OnRoleChanged(this);">
<option selected="selected" value="Preparer">Preparer</option>
<option value="Reviewer">Reviewer</option>
<option value="Approver">Approver</option>

</select></td>
c0vxltue

c0vxltue1#

首先,我想指出单独使用ie.busy是危险的。当您自动化网页时,.busy是非常不可靠的,我建议您在循环中也包含.readyState属性。
请看我使用.readyState < 4循环运行的测试:

注意到.Busy在前5行为true,然后在第6行变为false吗?这是您的代码认为加载网页的位置。然而,.readyState仍然是1 (相当于READYSTATE_LOADING
突然又变得忙碌起来,直到.readystate = 4READYSTATE_COMPLETE)。
我将.busy方法移到了一个单独的sub中,因为在浏览网页时经常调用这个方法。

Sub ieBusy(ie As Object)
    Do While ie.busy Or ie.readystate < 4
        DoEvents
    Loop
End Sub

Sub FillInternetForm()
    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")

    ie.navigate "website I'm navigating to"
    ie.Visible = True

    iebusy ie

    Set AllHyperLinks = ie.document.getElementsByTagName("A")
    For Each Hyper_link In AllHyperLinks
        If Hyper_link.innerText = "Reconciliations" Then
            Hyper_link.Click
            Exit For
        End If
    Next

    iebusy ie

    Dim mySelection As String, mySelObj As Object
    Set mySelObj = ie.document.getElementById("ctl00_MainContent_ucDashboardPreparer_ucDashboardSettings_ctl00_ddlRoles")

    'set your selection here
    mySelection = "Preparer"    'or Reviewer    or Approver
    Select Case mySelection
    Case "Preparer", "Reviewer", "Approver"
    Case Else
        MsgBox "Invalid Selection!"
        ie.Quit
        Exit Sub
    End Select

    mySelObj.Value = mySelection

End Sub

mySelObj是将设置选择的对象。

相关问题