使用值而不是索引从HTML下拉列表中选择的VBA代码 [英] VBA code to select from an HTML drop down, using value rather than index

查看:58
本文介绍了使用值而不是索引从HTML下拉列表中选择的VBA代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是VBA和HTML的新手.我正在编写一个VBA宏,该宏会在填写Web表单之前浏览网站.

I'm fairly new to VBA and HTML. I am writing a VBA macro which navigates through a website, before filling in a web form.

在导航期间,脚本需要从下拉菜单中选择一个选项.我目前正在使用以下代码(无疑很糟糕,但是功能强大),该代码在选择索引2的选项之前会找到正确的下拉菜单.

During navigation, the script needs to pick an option from a drop-down menu. I am currently using the following (no doubt awful, but functional) code, which finds the correct drop-down menu before selecting the option at index 2.

Set dropOptions = HTMLDoc.getElementsByTagName("select")
For Each op In dropOptions
If op.getAttribute("name") = "tilastojakso" Then
op.Focus
op.selectedIndex = 2
Exit For
End If
Next op

这是相关下拉列表的HTML:

And here is the HTML of the relevant dropdown:

<tr>
    <td>Statistical period</td>
    <td colspan="2"><select name="tilastojakso" >
<option value="2016-07">2016-07 (deadline 12.08.2016)</option>
<option value="2016-06">2016-06 (deadline 14.07.2016)</option>
<option value="2016-05">2016-05 (deadline 14.06.2016)</option>
<option value="2016-04">2016-04 (deadline 16.05.2016)</option>
<option value="2016-03">2016-03 (deadline 14.04.2016)</option>
<option value="2016-02">2016-02 (deadline 14.03.2016)</option>
<option value="2016-01">2016-01 (deadline 12.02.2016)</option>
<option value="2015-12">2015-12 (deadline 18.01.2016)</option>
<option value="2015-11">2015-11 (deadline 14.12.2015)</option>
<option value="2015-10">2015-10 (deadline 13.11.2015)</option>
<option value="2015-09">2015-09 (deadline 14.10.2015)</option>
<option value="2015-08">2015-08 (deadline 14.09.2015)</option>
<option value="2015-07">2015-07 (deadline 14.08.2015)</option>
<option value="2015-06">2015-06 (deadline 14.07.2015)</option>
<option value="2015-05">2015-05 (deadline 12.06.2015)</option>
<option value="2015-04">2015-04 (deadline 18.05.2015)</option>
<option value="2015-03">2015-03 (deadline 16.04.2015)</option>
</select></td>

问题:

我想基于选项值而不是索引从下拉列表中进行选择.假设我有一个名为"period"的变量,其中包含字符串"2016-04".我希望脚本选择具有与句点"中存储的字符串匹配的值的选项.我找不到我能理解的答案.

I want to select from the dropdown based on option value, rather than index. Let's say I have a variable called "period" which contains the string "2016-04". I want the script to pick the option with a value that matches the string stored in "period". I haven't been able to find an answer that I can understand.

推荐答案

更改

op.Focus
op.selectedIndex = 2 

op.Value = period 

@Jordan的答案已从评论移至社区Wiki

这篇关于使用值而不是索引从HTML下拉列表中选择的VBA代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆