我正在尝试使用VBA填写表格(只是为了更熟练地使用VBA进行编程)。我注意到当通过VBA检查单选按钮时,Web表单未更新隐藏字段。
更具体地说,在选中单选按钮后,隐藏字段不会变得可见。
在研究为什么会这样时,我读到:“当您以编程方式更改数据时,事件通常不会触发”。如果这个假设成立,那么手动或编程填写表格有什么区别?但是,如果这个假设是错误的,那么我需要在代码中进行哪些调整才能使单击该单选按钮后隐藏字段可见?
我正在使用的网站来自荷兰税务局:https : //www.belastingdienst.nl/wps/wcm/connect/nl/auto-en-vervoer/content/hulpmiddel-motorrijtuigenbelasting-berekenen
这是我的代码。
Sub Show_Hidden_Field()
'Declaration section
Dim htmlDoc As New MSHTML.HTMLDocument
Dim objShell, objShellWindows, objShellWindow As Object
Dim htmlOption As MSHTML.IHTMLElement
'Wait an extra 3 seconds so you can switch to the IE window
'and see what's going on
Application.Wait Now + TimeValue("0:00:03")
'Find the correct Internet Explorer window
Set objShell = CreateObject("Shell.Application")
Set objShellWindows = objShell.Windows
For Each objShellWindow In objShellWindows
If objShellWindow.Name = "Internet Explorer" Then
'Find this window
If objShellWindow.LocationURL = "https://www.belastingdienst.nl/wps/wcm/connect/nl/auto-en-vervoer/content/hulpmiddel-motorrijtuigenbelasting-berekenen" Then
'This the correct page. Get the content of page
Set htmlDoc = objShellWindow.document
Exit For
End If
End If
Next objShellWindow
'Find the radio button . . .
Set htmlOption = htmlDoc.getElementById("V1-1_True")
'. . . and check it.
htmlOption.Checked = True
'**********************************************************************
'I've also tried these options without succes.
'htmlOption.Click
'htmlOption.FireEvent ("onchange")
'Or set the focus to another field
'**********************************************************************
End Sub
您的代码有几个问题。第一个是您为单选按钮元素使用了错误的类型。
虽然htmlOption
是技术上一个MSHTML.IHTMLElement
,它更具体地说应该是类型:MSHTML.HTMLInputElement
。因此,将您的声明更改为:
Dim htmlOption As MSHTML.HTMLInputElement
对于您的实际问题,您应该使用.Click
。看一下developer.mozilla.org:
该
HTMLElement.click()
方法模拟在元素上的鼠标单击。当
click()
与受支持的元素(例如<input>
)一起使用时,它将触发元素的click事件。然后,此事件冒泡到文档树(或事件链)中较高的元素,并触发其单击事件。 (强调)
因此,您无需使用.Checked = True
,因为单击输入元素后,您不仅可以解决隐藏区域被显示的问题,还可以同时将值更改为True
。
因此,您将使用以下代码:
'Find the radio button . . .
Set htmlOption = htmlDoc.getElementById("V1-1_True")
'. . . and check it.
htmlOption.Click
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句