Excel VBA调用天气API二次运行报Run-time error '91'错误如何解决?
错误成因
- 核心触发点是降水节点不存在:OpenWeatherMap的XML返回结果仅在当前有降水(雨/雪)时才会返回
<precipitation>节点,无降水时该节点缺失,xmlresponse.SelectNodes("//current/precipitation/@mode")会返回空集合,直接取索引(0)的Text属性就会触发91错误,这也是首次请求成功、第二次失败的典型原因(两次请求时天气状态不同)。 - 变量定义不规范:
myurl被定义为Object类型,但实际赋值为字符串,属于隐性类型不匹配,存在运行隐患。 - 缺少基础校验逻辑:未判断HTTP请求是否成功、XML是否加载成功、目标节点是否存在,任意环节异常都会直接触发空对象引用错误。
- 对象实例化方式有隐患:使用
As New声明对象会导致对象实例残留,重复点击按钮时可能出现对象状态异常。
修复方案
直接替换为如下修正后的代码即可:
Private Sub getWeather_Click() ' 分开声明和实例化,避免对象残留 Dim xmlhttp As MSXML2.xmlhttp Dim myurl As String ' 修正为正确的字符串类型 Dim xmlresponse As DOMDocument Dim nodeList As IXMLDOMNodeList ' 用于提前判断节点是否存在 Set xmlhttp = New MSXML2.xmlhttp Set xmlresponse = New DOMDocument ' 配置XML加载规则 xmlresponse.async = False xmlresponse.validateOnParse = False myurl = "http://api.openweathermap.org/data/2.5/weather?apikey=ee9100bd8e6079ca3380ee1d145dda84&mode=xml&units=imperial&q=" & Range("F3").Value ' 发送请求并校验HTTP状态 xmlhttp.Open "GET", myurl, False xmlhttp.Send If xmlhttp.Status <> 200 Then MsgBox "接口请求失败,错误码:" & xmlhttp.Status GoTo Cleanup End If ' 校验XML是否加载成功 If Not xmlresponse.LoadXML(xmlhttp.responseText) Then MsgBox "XML解析失败:" & xmlresponse.parseError.reason GoTo Cleanup End If ' 温度节点取值 Set nodeList = xmlresponse.SelectNodes("//current/temperature/@value") If nodeList.Length > 0 Then Range("B10").Value = nodeList(0).Text Else Range("B10").Value = "无数据" End If ' 云量节点取值 Set nodeList = xmlresponse.SelectNodes("//current/clouds/@name") If nodeList.Length > 0 Then Range("B11").Value = nodeList(0).Text Else Range("B11").Value = "无数据" End If ' 降水节点取值,兼容无降水场景 Set nodeList = xmlresponse.SelectNodes("//current/precipitation/@mode") If nodeList.Length > 0 Then Range("B12").Value = nodeList(0).Text Else Range("B12").Value = "无降水" End If Cleanup: ' 释放对象,避免残留 Set nodeList = Nothing Set xmlresponse = Nothing Set xmlhttp = Nothing End Sub
内容的提问来源于stack exchange,提问作者christina.kz
相关产品推荐
相关产品推荐

