从HTML下拉菜单中选择的VBA代码

时间:2018-04-04 05:17:46

标签: vba excel-vba excel

我开始尝试编写VBA代码,并且从下拉列表中选择项目时遇到问题。它是一个动态下拉框,默认情况下,它是“无”,一旦在第一个框中进行选择,则使用相同的data-field =“taxonomy_id”打开另一个框,并选择新参数。

下拉列表的HTML代码:

<select class="select select-custom" data-field="taxonomy_id">
            <option value="">
                    None
            </option>

                <optgroup label="Select a category">
                    <option value="1">Accessories</option>
                    <option value="66">Art &amp; Collectibles</option>
                    <option value="132">Bags &amp; Purses</option>
                    <option value="199">Bath &amp; Beauty</option>
                    <option value="323">Books, Movies &amp; Music</option>
                    <option value="374">Clothing</option>
                    <option value="562">Craft Supplies &amp; Tools</option>
                    <option value="825">Electronics &amp; Accessories</option>
                    <option value="891">Home &amp; Living</option>
                    <option value="1179">Jewelry</option>
                    <option value="1250" selected="">Paper &amp; Party Supplies</option>
                    <option value="1351">Pet Supplies</option>
                    <option value="1429">Shoes</option>
                    <option value="1552">Toys &amp; Games</option>
                    <option value="1633">Weddings</option>
            </optgroup>
        </select>

我用来选择“Paper&amp; Party Supplies”的代码是:

IE.document.all("taxonomy_id").Value = "1250"

我上面使用的代码无法在初始下拉框中选择项目。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

假设提供任何解决方案总是一项艰巨的任务。但是,试试吧。它应该从下拉选项中选择Paper & Party Supplies

Sub Select_Item()
    Dim post As Object, elem As Object

    With CreateObject("InternetExplorer.Application")
        .Visible = True
        .navigate "webpage_link"  ''Try with your URL
        While .Busy = True Or .readyState < 4: DoEvents: Wend

        ''If the content of that page generates dynamically, make sure to put here some delay

        Set post = .document.querySelector("select[data-field='taxonomy_id']")
        For Each elem In post.getElementsByTagName("option")
             If InStr(elem.Value, "1250") > 0 Then elem.Selected = True: Exit For
         Next elem
    End With
End Sub