从下拉列表中选择项目时如何启动更改事件?

How to initiate on change event when selecting item from drop down list?

我试图在从下拉菜单中选择货币值时触发 "on change" 事件。这将更新该页面上反映货币价值的迷你电子表格。但是,当通过 VBA 更改值时,不会触发 jscript。我正在使用 IE 来执行此操作。

  Set objIE = New InternetExplorer
    objIE.Visible = True
    objIE.navigate "https://www.reuters.com/markets/currencies"
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop

    'Settlement Currency is Hard Coded to GBP
    SettCcy = "GBP"
    'Set Expression Currency
    expCcy = "EUR"
    'Set Target Currency
    targetCcy = "USD"

    On Error GoTo ResetIE

    If expCcy <> SettCcy And expCcy <> targetCcy Then

        'Set the rate refresher
        Set clicker = objIE.document.getElementsByClassName("CurrencyCalculator-currency-swap-2yw2I")(0)

        'Set the Expression Currency
        For Each o In objIE.document.getElementsByTagName("select")(1) 'Sets Expression Currency
            If o.Value = expCcy Then 
                o.Selected = True
                o.FireEvent "onchange"
                Exit For
            End If
        Next

我所需要的只是通过 VBA 更改值后,页面将以与手动操作时相同的方式更新。

请尝试使用dispatchEvent method将change事件派发给select元素,然后触发onchange事件。

示例代码如下(大家可以参考修改,我这边效果很好):

Public Sub ClickTest()

    Dim  ie As Object, evtChange As Object

    Dim item As Object

    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = True
        .Navigate2 "<the website url>"

        While .Busy Or .readyState <> 4: DoEvents: Wend

        Set evtChange = .Document.createEvent("HTMLEvents")
        evtChange.initEvent "change", True, False

        'get the select element. Please note the index, it is starting from 0.
        Set item = ie.Document.getElementsByTagName("select")(0)

        expCcy = "EUR"

        'Set the Expression Currency
        For Each o In item 'Sets Expression Currency
            If o.Value = expCcy Then
                o.Selected = True
                o.dispatchEvent evtChange
                Exit For
            End If
        Next        
    End With
End Sub

这样的网站资源:

<select id="ddlCurrency" onchange="ddlCurrencyChange()" >
    <option value="GBP">GBP</option>
    <option value="EUR">EUR</option>
    <option value="USD">USD</option>
</select>

<script>

    function ddlCurrencyChange() {
        document.getElementById("result").innerHTML += "change event triggered... <br /> selected value is " + document.getElementById("ddlCurrency").value + "<br/>";
    }
</script>