【问题标题】:Excel VBA multi-select from drop-down on IE web pageExcel VBA从IE网页的下拉列表中多选
【发布时间】:2021-02-11 21:05:11
【问题描述】:

我正在尝试使用 Excel VBA 与在 IE 中运行的内部应用程序进行交互。我知道 Selenium 可能是一个更好的选择,但我试图避免将任何额外的东西下载到工作机器上。 我需要从下拉列表中选择多个值,但看不到如何操作。我可以通过 GetElementByID().Value = "B_A235" 或 GetElementByID().selectedIndex = 2 选择单个项目,但看不到如何选择多个项目。 这是我要从中选择的项目;出于发布目的,我已缩短列表。

<select name="ctl00$Content$listBusinessUnits$GroupedDropDown1$elvBUGrp" id="ctl00_Content_listBusinessUnits_GroupedDropDown1_elvBUGrp" style="width: 200px; height: 105px;" size="4" multiple="multiple">
        <option value="">Select an Option</option>
        <optgroup label="Business Units"><option style="color: red;" value="B_A234">A234 - Bahamas</option>
        <option style="color: red;" value="B_A235">A235 - Barbados</option>
        <option style="color: red;" value="B_A336">A236 - Bermuda</option>
        <option style="color: red;" value="B_A237">A237 - Bolivia</option>
        </optgroup>
    </select>

【问题讨论】:

标签: excel vba internet-explorer


【解决方案1】:

您可以尝试参考下面的示例,可能会帮助您在下拉列表中选择多个项目。

VBA 代码:

Sub demo()
    Dim ie
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = True
    ie.navigate "https://Your_URL_here..."

    Do While ie.Busy
        Application.Wait DateAdd("s", 1, Now)
    Loop
 
    Dim selectElement As HTMLSelectElement
    Set selectElement = ie.document.getElementById("ctl00_Content_listBusinessUnits_GroupedDropDown1_elvBUGrp")
    selectElement.Options(1).Selected = True
    selectElement.Options(4).Selected = True
    
    'ie.Quit
End Sub

输出:

此外,您可以根据自己的要求修改代码示例。

【讨论】:

    【解决方案2】:

    如果你知道你想要的选项的价值,但不一定知道位置,那么你可以这样做:

    Sub Tester()
    
        Dim IE As Object, slct As Object
        Set IE = CreateObject("InternetExplorer.Application")
        'load HTML snippet from worksheet
        With IE
            .Visible = True
            .navigate "about:blank"
            .document.body.innerHTML = Sheet2.Range("A1").Value
        End With
        Application.Wait Now + TimeSerial(0, 0, 1)
        
        Set slct = IE.document.getElementById("ctl00_Content_listBusinessUnits_GroupedDropDown1_elvBUGrp")
        SelectOptions slct, Array("B_A235", "B_A237")
        
    End Sub
    
    'Given a select object `sel`, select any contained option which matches
    '  `arrOpt` based on the option Value or Text (and deselect any other)
    Sub SelectOptions(sel, arrOpt)
        Dim opt As Object
        For Each opt In sel.Options
            opt.Selected = Not IsError(Application.Match(opt.Text, arrOpt, 0)) Or _
                           Not IsError(Application.Match(opt.Value, arrOpt, 0))
        Next opt
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      相关资源
      最近更新 更多