简体   繁体   中英

select drop-down list by text not value

I am trying to write an Excel VBA script to navigate to a website and select from a drop-down list using the text in the list item, NOT the value of the index. By examining the HTML code, I can see that the values in the drop-down list appear to be integers with no recognizable pattern and do not appear to correlate to the text shown for the entry in the drop-down list.

<option value="246">new2</option>
<option value="245">new</option>
<option value="196">test</option>

I can successfully use the following command:

ieDoc.getElementById("viewMaintainFixedCombustible_fixedCombustible_fireZoneId").Value = 246

To select the item "new2" from the drop-down list, by sending the value 246. Or, I could send 245 to select "new". However, the elements in the list are always changing, so selecting by value (246, 245, etc.) is impractical. Thus, I am searching for a way to select an entry from the drop-down list (eg "new2") by sending the text name of the entry (eg "new2") in VBA.

Does anyone have a method for how to do this?

Try below sample code to set dropdown list by text.

    Set drp =ieDoc.getElementById("<id of your dropdown>")
    For x = 0 To drp.Options.Length - 1
        If drp.Options(x).Text = "new2" Then
            drp.selectedIndex = x
            Exit For
        End If
    Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM