【问题标题】:Select an option from a dropdown in IE and triggering a function从 IE 的下拉列表中选择一个选项并触发一个功能
【发布时间】:2020-05-09 20:10:35
【问题描述】:

所以,我是 VBA 的 IE 自动化的新手。我将尝试非常具体地回答我的问题。最近,我一直在尝试登录一个网站,然后从下拉列表中选择一个月。我可以从下拉列表中选择一个选项。但是,当我单击搜索按钮时,结果显示的不是我使用 VBA 选择的值,而是网页上最初存在的值。通常,如果一个人访问该网站,他必须单击下拉菜单并选择相关时期,然后单击搜索按钮。 我也尝试过 FireEvent“onchange”,但这似乎没有任何效果。 我附上了 VBA 的相关部分以及相关的 HTML。

请指导我如何选择时间段。

VBA 代码:

Set e = IE.document.getElementsByName("fin")(0)
 e.Focus
 e.selectedIndex = 1
 e.FireEvent ("onchange")

HTML:

<select name="fin" class="form-control ng-pristine ng-not-empty ng-valid ng-valid-required ng-touched" 
data-ng-model="finyr" data-ng-options="item.year for item in years"
value="item.year" data-ng-change="hidedata()" required="">
<option label="2019-20" value="object:143" selected="selected">2019-20</option>
<option label="2018-19" value="object:144">2018-19</option>
<option label="2017-18" value="object:145">2017-18</option>
<option label="2020-21" value="object:146">2020-21</option></select>

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    有两种方法。首先,您可以在 url 中设置所需的参数。比您不需要在这里执行的步骤。如果页面使用Get 与服务器通信,则该解决方案有效。如果它使用Post,你必须按照你的要求去做。

    您可以通过手动执行所有需要的步骤来检查它是否通过 url 参数工作。之后,查看您在浏览器中找到的网址。如果有参数列表,则以问号 (?) 开头。以下所有参数均以与号 (&) 开头。

    如果您必须通过代码执行此操作,请尝试以下操作:

    Sub SelectFromDropdown()
    
      Dim url As String
      Dim browser As Object
      Dim nodeSelect As Object
    
      url = "Your url here"
    
      'Initialize Internet Explorer, set visibility,
      'call URL and wait until page is fully loaded
      Set browser = CreateObject("internetexplorer.application")
      browser.Visible = True
      browser.navigate url
      Do Until browser.readyState = 4: DoEvents: Loop
    
      'Get the dropdown and select the wanted entry by index
      'Indexes beginn with 0
      '(Code lines from your question)
      Set nodeSelect = browser.document.getElementsByName("fin")(0)
      nodeSelect.selectedIndex = 1
    
      'It is likely that the change to the page must be communicated
      'via an HTML event. This is probably the change event
      'FireEvent doesn't work on most pages
       Call TriggerEvent(browser.document, nodeSelect, "change")
    End Sub
    

    这个过程触发html事件:

    Private Sub TriggerEvent(htmlDocument As Object, htmlElementWithEvent As Object, eventType As String)
    
      Dim theEvent As Object
    
      htmlElementWithEvent.Focus
      Set theEvent = htmlDocument.createEvent("HTMLEvents")
      theEvent.initEvent eventType, True, False
      htmlElementWithEvent.dispatchEvent theEvent
    End Sub
    

    【讨论】:

    • 谢谢。这行得通。我从字面上搜索尽可能多的地方,但找不到解决方案。真的,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 2015-03-18
    相关资源
    最近更新 更多