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

埃尔金·卡汉吉罗夫(Elgin Cahangirov)

我正在尝试使用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

该脚本返回运行时错误91。它说:“对象变量或未设置块变量”。当我调试时,运行在“下一个天气”语句之前的行处停止。在我已经设置了“ wshape”变量的同时,为什么这个脚本返回这样的错误?

煎蛋卷

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

XML树查看器

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章