Excel VBA和IE 11 – 在下拉菜单中select值后无法刷新页面

我正在尝试获得WorldRemit为一对货币提供的货币汇率。 我想要更改网页左上angular“发送自”下拉列表中的值。 ( https://www.worldremit.com/en/South-Africa )

我无法使用.Selected = True.Selected = Trueselect下拉选项,因此使用了.SelectedIndex 。 select该值后,我无法触发刷新页面的更改事件。 如果有人能帮我弄明白这一点,那会很棒。

导航到页面的代码:

 Set ie = CreateObject("InternetExplorer.Application") ie.Visible = True ie.navigate "https://www.worldremit.com/en/South-Africa" While ie.busy DoEvents Wend Set HTMLdoc = ie.document 

使用.SelectedIndex属性select选项的代码:

 Dim fromSelect As HTMLSelectElement Set fromSelect = HTMLdoc.getElementById("selectFrom") optionIndex = Find_Select_Option(fromSelect, "Germany") If optionIndex >= 0 Then fromSelect.selectedIndex = optionIndex fromSelect.FireEvent ("onchange") ' this doesn't work End If 

用于select选项的函数(在上面的代码中使用):

 Function Find_Select_Option(selectElement As HTMLSelectElement, optionText As String) As Integer Dim i As Integer Find_Select_Option = -1 i = 0 While i < selectElement.Options.Length And Find_Select_Option = -1 DoEvents If LCase(Trim(selectElement.Item(i).Text)) = LCase(Trim(optionText)) Then Find_Select_Option = i i = i + 1 Wend End Function 

编辑#1:包含有问题的元素的HTML片段是

 <select id="selectFrom" data-track-field-name="from country" data-track-event="change">...</select> 

试试看,这是我的工作。 有时使用jQuery更容易一些,特别是当页面也使用jQuery的时候。

你可以使用IE的execScript函数来使用jQuery。 见下文:

  Public Sub test() Dim IE As Object: Set IE = CreateObject("InternetExplorer.Application") With IE .Visible = True .navigate "https://www.worldremit.com/en/South-Africa" 'Wait for the page to load While .busy Or .readyState <> 4 Application.Wait (Now() + TimeValue("00:00:01")) DoEvents Wend 'Use JQuery to find the element based on ID, then make the Selected property true 'Once that is done, call the change event in jQuery .document.parentWindow.execScript "$('#selectFrom option:contains(Germany)').prop('selected','True')" .document.parentWindow.execScript "$('#selectFrom option:contains(Germany)').change()" End With End Sub 

显然, FireEvent不能很好地处理IE 11,所以需要使用CreatEvent + initEvent + dispatchEvent

下面的工作代码片段:

 Dim fromSelect As HTMLSelectElement Dim evt As Object Set evt = HTMLdoc.createEvent("HTMLEvents") evt.initEvent "change", True, False Set fromSelect = HTMLdoc.getElementById("selectFrom") optionIndex = Find_Select_Option(fromSelect, "Germany") If optionIndex >= 0 Then fromSelect.selectedIndex = optionIndex fromSelect.dispatchEvent evt End If