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

使用VBA获取内网网页输入框值时遇运行时错误'91'求助

VBA获取内网输入框值时运行时错误'91'的解决思路

错误本质

运行时错误'91'是因为代码尝试访问的对象未被成功定位(返回Nothing),可能是元素定位逻辑错误、网页未加载完成,或DOM结构与预期不符。

现有写法问题分析

  • 第一种写法:

    TerminPlatnosci = Trim(Doc.getelementsByName("section-36-control$xf-771$xf-784$xml_termin_platnosci-control$xforms-input-1")(0).Value)
    

    若getElementsByName返回的集合为空,直接索引(0)会触发错误91,未做存在性判断。

  • 第二种写法:

    TerminPlatnosci = Trim(Doc.getElementsByTagName("tr")(0).getElementsByName("input id")(0).getAttribute("value"))
    

    getElementsByName的参数"input id"不是合法的元素name值,且getElementsByTagName("tr")(0)不一定包含目标输入框,逻辑完全错误。

  • 第三种写法:

    TerminPlatnosci = Trim(Doc.querySelector("input[name='section-36-control$xf-771$xf-784$xml_termin_platnosci-control$xforms-input-1']").getAttribute("value"))
    

    CSS选择器中$是特殊字符(表示结尾匹配),未转义会导致定位失败;且未判断querySelector是否返回有效对象,直接调用方法触发错误。

修正后的代码示例

先判断元素是否存在,再执行取值操作:

Dim targetInput As Object
Dim TerminPlatnosci As String

' 等待网页完全加载
Do While Doc.ReadyState <> "complete"
    DoEvents
Loop

' 优先用getElementsByName查找
Set targetInput = Doc.getelementsByName("section-36-control$xf-771$xf-784$xml_termin_platnosci-control$xforms-input-1")
If targetInput.Length > 0 Then
    TerminPlatnosci = Trim(targetInput(0).Value)
Else
    ' 转义CSS选择器中的$符号后用querySelector查找
    Set targetInput = Doc.querySelector("input[name='section-36-control\$xf-771\$xf-784\$xml_termin_platnosci-control\$xforms-input-1']")
    If Not targetInput Is Nothing Then
        TerminPlatnosci = Trim(targetInput.getAttribute("value"))
    Else
        TerminPlatnosci = "未找到目标输入框"
    End If
End If

额外排查项

  • 确认目标输入框的name属性:打开网页开发者工具(F12),直接查看输入框的实际name值,避免拼写错误或动态生成的属性变化。
  • 检查是否存在iframe:若输入框嵌套在iframe内,需先切换到对应iframe对象(Set Doc = iframeObj.Document)再执行元素查找。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 15:01:08