【问题标题】:Excel VBA: Check all check boxes on Web PageExcel VBA:选中网页上的所有复选框
【发布时间】:2018-07-12 14:31:55
【问题描述】:

我正在尝试通过 VBA 检查网页上所有可用的复选框,因为名称约定似乎不是我可以选择的一种。但是我似乎无法得到任何工作。我可以登录网站并导航到我想要的网站部分,但无法跨越这个障碍。任何帮助将不胜感激。以下是网页源代码。

       <li data-product-family="30yr"
            data-product-amortizationTerm="30"
            data-product-type="Conventional"
            data-product-amortizationType="Fixed"

        >
        <label>
        <input type="checkbox" 
            value="154232" 
            class="product-Conventional product-item" 
            data-authorized-remittance-types="ActualActual "
            />30-Year Fixed Rate - 110k Max Loan Amount</label>
        </li>

我尝试编写(已编辑)的 VBA...我目前正在使用的代码:

Public Sub TestIE()
Dim IE As Object
Dim aNodeList As Object, i As Long


' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")

' You can uncoment Next line To see form results
IE.Visible = False

' Send the form data To URL As POST binary request
IE.Navigate "https://"

' Statusbar
Application.StatusBar = "Page is loading. Please wait..."

' Wait while IE loading...
Do While IE.Busy
    Application.Wait DateAdd("s", 1, Now)
Loop

IE.Visible = True

Set aNodeList = IE.document.querySelectorAll("input[type=checkbox]")
If aNodeList Is Nothing Then Exit Sub
For i = 0 To aNodeList.Length
aNodeList.Item(i).Checked = True
Next i 
End Sub

【问题讨论】:

  • 您的Exit For 指示循环在第一次匹配时退出。
  • 谢谢比尔,我对此有些陌生。我希望如果这是唯一的问题,它至少会检查第一个复选框,但它似乎没有这样做。运行代码时出现自动化错误和未指定的错误。
  • I cannot seem to get anything to workbut cannot cross this hurdle:这些声明并没有给我们很多工作。您收到错误消息吗?运行代码时会发生什么?另外,不要使用Click,您应该可以使用.Checked 属性来设置复选框.. 除非您使用嵌入元素?
  • 见上面的错误。我尝试从“点击”更改为“已检查”,但无济于事。确切的错误读取:运行时错误'-2147467259(80004005)':自动化错误未指定错误
  • 澄清一下,将元素设置为选中状态,您可以将其设置为:objElement(i).Checked = True

标签: excel vba web


【解决方案1】:

您可以尝试通过以下方式获取复选框的节点列表:

IE.document.querySelectorAll("input[type=checkbox]")

你可以沿着 nodeList 的 .Length 属性遍历它。

例如

Dim aNodeList As Object, i As Long
Set aNodeList = IE.document.querySelectorAll("input[type=checkbox]")
If aNodeList Is Nothing Then Exit Sub
For i = 0 To aNodeList.Length -1
    On Error Resume Next
    aNodeList.item(i).Checked  = True
    On Error GoTo 0
Next i

【讨论】:

  • QHarr,效果很好。也就是说,它确实创建了一个新错误:运行时错误 424 需要对象。有什么想法吗?不确定它是否试图连续循环?我用我现在使用的代码更新了原始帖子。
  • 我怀疑您可能必须将条件设置为:For i = 0 To aNodeList.Length - 1 也许?
  • 该死的我错过了。对不起。谢谢扎克!是的,它是从零开始的,所以你的长度为-1。您还可以“屏蔽”错误时继续下一步,检查复选框是否执行页面上的任何 JavaScript 是值得的。
  • 我建议这样做的唯一原因是因为我自己已经做过数百万次了:)
猜你喜欢
  • 2019-01-10
  • 2015-08-12
  • 2014-04-18
  • 2017-10-15
  • 2018-10-06
  • 1970-01-01
  • 2010-11-27
  • 2021-03-25
  • 2012-07-12
相关资源
最近更新 更多