Excel VBA 运行-时间错误91无法解决

Excel VBA run-time error 91 can't solve

我正在尝试使用 XML 从网站中提取数据。请看下面我的脚本:

脚本

Option Explicit

Private Sub btnRefresh_Click()
    Dim req As New XMLHTTP
    Dim resp As New DOMDocument
    Dim weather As IXMLDOMNode
    Dim ws As Worksheet: Set ws = ActiveSheet
    Dim wshape As Shape
    Dim thiscell As Range
    Dim i As Integer

    req.Open "GET", "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=myConfidentialToken&q=Baku&format=xml&num_of_days=5"
    req.send

    resp.LoadXML req.responseText

    For Each weather In resp.getElementsByTagName("weather")
        i = i + 1
        ws.Range("theDate").Cells(1, i).Value = weather.SelectNodes("date")(0).Text
        ws.Range("highTemps").Cells(1, i).Value = weather.SelectNodes("maxtempC")(0).Text
        ws.Range("lowTemps").Cells(1, i).Value = weather.SelectNodes("mintempC")(0).Text
        Set thiscell = ws.Range("weatherPicture").Cells(1, i)
        Set wshape = ws.Shapes.AddShape(msoShapeRectangle, thiscell.Left, thiscell.Top, thiscell.Width, thiscell.Height)
        wshape.Fill.UserPicture weather.SelectNodes("weatherIconUrl").Item(0).Text
    Next weather

End Sub

此脚本 returns 运行-时间错误 91。它说:"Object variable or With block variable not set"。当我调试时,运行ning 在 "next weather" 语句之前的行停止。为什么这个脚本 returns 这样的错误,而我已经设置了我的 "wshape" 变量?

正如@JohnRC 指出的那样,每个 <weather> 节点内有一组 <hourly> 节点,每个 <hourly> 节点依次包含 <weatherIconUrl>。您可以将响应 XML 保存到文件中,并使用任何在线 XML 树查看器查看结构:

看看下面的示例,添加了一个嵌套循环以从每个 <hourly> 节点获取 <weatherIconUrl>

Option Explicit

Private Sub btnRefresh_Click()

    Dim oReq As Object
    Dim sResp As String
    Dim oDoc As Object
    Dim oData As Object
    Dim cDays As Object
    Dim oDay As Object
    Dim cHours As Object
    Dim oHour As Object

    Set oReq = CreateObject("MSXML2.XMLHTTP")
    oReq.Open "GET", "http://api.worldweatheronline.com/premium/v1/weather.ashx?key=e11be04676ad49038f9175720181600&q=saint-petersburg&format=xml&num_of_days=5", False
    oReq.Send
    sResp = oReq.ResponseText
    Set oDoc = CreateObject("MSXML2.DOMDocument")
    oDoc.LoadXML sResp
    Set oData = oDoc.getElementsByTagName("data")(0)
    Set cDays = oData.SelectNodes("weather")
    For Each oDay In cDays
        Debug.Print oDay.SelectNodes("date")(0).Text
        Debug.Print oDay.SelectNodes("maxtempC")(0).Text
        Debug.Print oDay.SelectNodes("mintempC")(0).Text
        Set cHours = oDay.SelectNodes("hourly")
        For Each oHour In cHours
            Debug.Print vbTab & oHour.SelectNodes("time")(0).Text
            Debug.Print vbTab & oHour.SelectNodes("tempC")(0).Text
            Debug.Print vbTab & oHour.SelectNodes("weatherIconUrl")(0).Text
        Next
    Next

End Sub