2016-10-03 86 views
1

我試圖獲得WorldRemit爲一對貨幣提供的貨幣兌換率。我想更改網頁左上角的「發送自」下拉列表中的值。 (https://www.worldremit.com/en/South-AfricaExcel VBA和IE 11 - 在下拉列表中選擇值後無法刷新頁面

我無法使用.Selected = True.Click選擇下拉選項,所以使用.SelectedIndex。選擇值後,我無法觸發刷新頁面的更改事件。如果有人能幫我弄清楚這一點,那會很棒。

代碼用於導航到頁:

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屬性選擇選項:

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 

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 

功能用於選擇的選項(在上面的代碼中使用)

編輯#1:包含相關元素的HTML片段是

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

先給下拉元素「焦點」,觸發「OnClick」事件,並給出另一個元素「焦點」。 –

+0

在另一個元素上嘗試了'Focus' +'OnClick' +'Focus',但沒有奏效。 此外,當我在即時窗口中檢查它們時,下拉列表的'Element.OnClick'和'Element.OnChange'屬性返回'Null'。 – cattlesnake

回答

0

試試看,這是對我的結局。有時候使用jQuery更容易一些,特別是當頁面也使用jQuery的時候。

您可以使用jQuery通過使用IE的execScript函數。請看下圖:

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 
+0

非常感謝!找到另一種方式,但肯定會檢查出來以及:) 此外,它似乎像您的代碼將與舊版本的IE以及。 – cattlesnake

+0

應該更快,代碼也更少。學習jQuery(如果你還不知道它)會爲你節省一些頭痛的問題,它們會迭代元素並處理不存在的事件作爲IE對象的一部分。您的解決方案如下,您需要創建一個新的事件「更改」,然後再觸發它。 –

+0

的確如此。將嘗試拿起一些jQuery技能。再次感謝。 – cattlesnake

0

顯然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 
相關問題