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

Excel VBA提取网页td标签文本报运行时错误424的问题咨询

错误核心原因

  • 声明了Doc对象但未完成赋值,全程没有Set Doc = IE.document语句,调用Doc相关方法时触发对象缺失报错
  • DOM方法拼写错误,获取多元素的方法为复数形式getElementsByTagName,你使用的单数形式无法正常调用
  • 点击Lookup按钮后没有等待页面加载完成就直接读取DOM节点,找不到目标元素会触发报错
  • 外层循环变量i和内层遍历input的循环变量重名,会打乱外层循环的执行逻辑

前置准备

首先在VBA编辑器的「工具」-「引用」中,勾选Microsoft HTML Object Library,确保HTMLDocument类型可以正常识别。如果不想手动勾选引用,也可以将Dim Doc As HTMLDocument修改为Dim Doc As Object,使用后期绑定方式调用。

修正后代码

Sub Macro1()
    Dim IE As Object
    Set IE = CreateObject("InternetExplorer.Application")
    Dim Doc As HTMLDocument
    IE.navigate "https://lambda.byu.edu/ae/prod/person/cgi/personLookup.cgi"
    IE.Visible = True
    '等待页面初始加载完成
    While IE.Busy Or IE.readyState <> 4
        DoEvents
    Wend
    '给Doc对象赋值,这步是你之前缺失的
    Set Doc = IE.document
    
    Dim i As Integer, iNumberOfLoops As Integer
    iNumberOfLoops = Sheets("Extract").Range("D2").Value
    
    For i = 1 To iNumberOfLoops
        Doc.all("inpSearchPattern").Value = ThisWorkbook.Sheets("Extract").Range("A1")
        Set objCollection = Doc.getElementsByTagName("input")
        Dim j As Integer
        '内层循环换用j做变量,避免和外层i冲突
        j = 0
        While j < objCollection.Length
           If (objCollection(j).Value = "Lookup" And objCollection(j).Type = "button") Then
               Set objElement = objCollection(j)
           End If
            j = j + 1
        Wend
        objElement.Click
        '点击后等待搜索结果页面加载完成
        While IE.Busy Or IE.readyState <> 4
            DoEvents
        Wend
        '修正方法名为复数形式
        Dim aA As String
        aA = Trim(Doc.getElementsByTagName("td")(0).innerText)
        Sheets("Sheet1").Range("C6").Value = aA
    Next i
    '运行完成后释放对象
    IE.Quit
    Set IE = Nothing
    Set Doc = Nothing
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:45:04