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

如何用VBA填充HTML自动完成字段?ICAO碳计算器宏报错解决

解决ICAO碳计算器宏的字段填充问题

首先,你的代码报错「对象不支持该属性或方法」,主要有两个核心原因:

  • IE的Document对象没有getElementByName方法,正确写法是getElementsByName(注意复数形式),它返回一个元素集合,必须通过索引(比如(0))获取单个元素;
  • 出发/到达城市字段是带自动提示的动态输入框,直接赋值后不会触发网站的自动识别逻辑,必须配合事件触发,甚至需要主动选择下拉提示中的选项。

下面是修正后的完整代码,包含字段填充、自动提示选择的完整逻辑:

Sub get_CO2()
    Dim ie As Object
    Dim departureInput As Object, arrivalInput As Object
    Dim dropdownOptions As Object
    
    Set ie = New InternetExplorerMedium
    ie.Navigate "https://applications.icao.int/icec"
    
    ' 增加超时处理,避免页面加载卡住时无限等待
    Dim startTime As Date
    startTime = Now
    Do While ie.ReadyState <> 4 Or ie.Busy
        DoEvents
        If DateDiff("s", startTime, Now) > 10 Then Exit Do ' 10秒超时退出
    Loop
    
    ie.Visible = True
    
    With ie.Document
        ' 填充乘客数量和航程类型
        .getElementById("passengerNo").Value = 7
        .getElementById("select1").selectedIndex = 1
        .getElementById("select2").selectedIndex = 1
        
        ' 定位出发城市输入框(getElementsByName返回集合,取第一个元素)
        Set departureInput = .getElementsByName("frm1")(0)
        departureInput.Value = "China" ' 可输入国家名称或机场代码
        
        ' 触发input事件,让网站加载自动提示列表
        Call ie.Document.parentWindow.execScript("arguments[0].dispatchEvent(new Event('input'));", "javascript", departureInput)
        DoEvents ' 等待下拉列表加载完成
        
        ' 获取并点击第一个自动提示选项
        Set dropdownOptions = .getElementsByClassName("ui-menu-item")
        If dropdownOptions.Length > 0 Then
            dropdownOptions(0).Click
        End If
        
        ' 同理处理到达城市
        Set arrivalInput = .getElementsByName("to1")(0)
        arrivalInput.Value = "Japan"
        Call ie.Document.parentWindow.execScript("arguments[0].dispatchEvent(new Event('input'));", "javascript", arrivalInput)
        DoEvents
        If dropdownOptions.Length > 0 Then
            dropdownOptions(0).Click
        End If
        
        ' 点击计算按钮
        .getElementById("computeByInput").Click
    End With
    
    ' 释放对象,避免内存泄漏
    Set departureInput = Nothing
    Set arrivalInput = Nothing
    Set dropdownOptions = Nothing
    Set ie = Nothing
End Sub

关键细节说明:

  • 元素定位:对于名称为frm1/to1的输入框,必须用getElementsByName("xxx")(0)获取,因为getElementByName不是IE DOM的合法方法;
  • 动态输入框处理:这类带自动提示的输入框依赖JavaScript事件(比如input、keyup)加载下拉选项,所以赋值后需要用execScript触发对应事件;
  • 自动提示选择:网站的自动提示选项统一使用ui-menu-item类名,通过getElementsByClassName获取集合后,直接点击第一个元素即可;
  • 超时机制:增加10秒超时逻辑,避免页面加载异常时脚本无限等待。

关于未知机场代码的问题:

完全可以输入国家名称(比如"China"、"Japan"),网站会自动列出该国家的机场选项,上面的代码已经实现了「输入国家名称后选择第一个显示选项」的逻辑。

内容的提问来源于stack exchange,提问作者noel.H

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:55:39