问题描述
我正在尝试从下拉菜单中选择货币值来触发更改时"事件.这将更新该页面上的迷你电子表格,以反映货币的价值.但是,通过VBA更改值时不会触发jscript.我正在使用IE来做到这一点.
I'm trying to trigger "on change" event upon selecting currency value from drop-down menu. This would update the mini spreadsheet on that page reflecting the value of the currency. However when changing the value through VBA jscript is not being triggered. I'm using IE to do this.
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更改值后,页面将以与手动执行时相同的方式进行更新.
All I need is that upon changing the value through VBA the page would update the same way as it would when doing it manually.
推荐答案
请尝试使用 dispatchEvent方法,将更改事件分派给select
元素,然后触发onchange事件.
Please try to use the dispatchEvent method to dispatch the change event to the select
element, then trigger the onchange event.
下面的示例代码(您可以参考并对其进行修改,它对我而言效果很好):
Sample code as below (you could refer to it and modify it, it works well on my side):
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>
这篇关于从下拉列表中选择项目时如何启动更改事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!