You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA抓取嵌套DIV页面触发Run-time error '91'问题求助

错误原因排查与修复方案

核心错误:混淆CSS类名与ID属性

你代码里用getElementByID("fieldgroup ")查找容器,但目标页面中这个外层div的属性是class="fieldgroup ",而非id属性。getElementByID仅匹配带有id标记的元素,导致QuestionList被赋值为Nothing,后续访问.Children时触发"Run-time error '91'"(对象变量未初始化)。

修复步骤

  1. 修正元素查找方式:将ID查找改为类名查找,使用getElementsByClassName方法(返回元素集合,需通过索引取第一个匹配项):

    ' 原错误代码
    ' Set QuestionList = html.getElementByID("fieldgroup ")
    ' 修正为
    Set QuestionList = html.getElementsByClassName("fieldgroup ")(0)
    
  2. 简化子元素遍历逻辑:原代码用Question.all遍历所有子元素效率低下,可直接通过类名精准定位fieldlabel和fieldvalue:

    For Each Question In Questions
      If Question.className = "fieldrow _text-field" Then
        Cells(RowNumber, 1).Value = Trim(Question.getElementsByClassName("fieldlabel")(0).innerText)
        Cells(RowNumber, 2).Value = Trim(Question.getElementsByClassName("fieldvalue")(0).innerText)
        RowNumber = RowNumber + 1
      End If
    Next
    
  3. 强化页面加载等待:原有的READYSTATE_COMPLETE等待可能无法覆盖动态加载内容,补充双重等待逻辑:

    ' 原有等待循环后添加
    Do While ie.Busy Or ie.READYSTATE <> READYSTATE_COMPLETE
        DoEvents
    Loop
    ' 按需添加固定等待时间(根据页面加载速度调整)
    Application.Wait Now + TimeValue("00:00:02")
    

修正后的核心代码片段

' 设置表头
Range("A3").Value = "Field"
Range("B3").Value = "Values"

' 修正:通过类名获取外层容器
Set QuestionList = html.getElementsByClassName("fieldgroup ")(0)    
Set Questions = QuestionList.Children

RowNumber = 4

For Each Question In Questions
  If Question.className = "fieldrow _text-field" Then
    ' 直接提取标签与对应值
    Cells(RowNumber, 1).Value = Trim(Question.getElementsByClassName("fieldlabel")(0).innerText)
    Cells(RowNumber, 2).Value = Trim(Question.getElementsByClassName("fieldvalue")(0).innerText)
    RowNumber = RowNumber + 1
  End If
Next

内容的提问来源于stack exchange,提问作者Chasester

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 14:47:21