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

VBA创建HTMLDocument对象触发Run-time error '429'错误求助

解决VBA中创建HTMLDocument对象时的Run-time error '429'问题

问题详情

Run-time error '429'. ActiveX component can't create object

错误触发语句:

Set html = CreateObject("HTMLDocument")

完整报错代码:

Sub GetCurrentGoldPrice()
    Dim xmlhttp As Object
    Dim html As Object
    Dim gold_price As String
    
    Set xmlhttp = CreateObject("MSXML2.XMLHTTP")
    Set html = CreateObject("HTMLDocument")
    
    xmlhttp.Open "GET", "https://goldprice.org/", False
    xmlhttp.send
    
    html.body.innerHTML = xmlhttp.responseText
    gold_price = html.querySelector("#gold-price").innerText
    
    MsgBox "The current gold price is " & gold_price
    
    Set xmlhttp = Nothing
    Set html = N ' 此处存在笔误,正确应为 Set html = Nothing
End Sub

解决方法

1. 重新注册MSHTML组件

HTMLDocument对象依赖mshtml.dll组件,未正确注册会导致创建失败:

  • 以管理员身份打开命令提示符(CMD)
  • 执行命令:
    regsvr32.exe mshtml.dll
    
  • 重启Office应用后重试代码

2. 替换HTMLDocument为InternetExplorer对象

若组件注册无效,可改用IE对象解析HTML,兼容性更强:

Sub GetCurrentGoldPrice_Fixed()
    Dim ie As Object
    Dim gold_price As String
    
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = False ' 隐藏浏览器窗口
    
    ie.Navigate "https://goldprice.org/"
    ' 等待页面加载完成
    Do While ie.Busy Or ie.ReadyState <> 4
        DoEvents
    Loop
    
    gold_price = ie.document.querySelector("#gold-price").innerText
    MsgBox "The current gold price is " & gold_price
    
    ie.Quit
    Set ie = Nothing
End Sub

3. 调整Office信任中心设置

  • 打开Excel,依次进入「文件」→「选项」→「信任中心」→「信任中心设置」
  • 「宏设置」中启用宏(测试时可选择「启用所有宏」,日常建议保持「禁用所有宏,并发出通知」)
  • 「ActiveX设置」中选择允许控件运行的选项,如「提示我启用所有控件」

4. 修复Office安装

若以上方法无效,可能是Office组件损坏:

  • 打开「控制面板」→「程序和功能」,找到Office安装项
  • 右键选择「更改」,执行「快速修复」或「联机修复」,完成后重启电脑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:47:24