EXCEL VBA 网络获取JSON并解读

来源:简书 分类: 文章浏览史 发布时间:2020-08-20 14:49:48 最后更新:2020-08-20 浏览:73
转载声明:
本文为摘录自“简书”,版权归原作者所有。
温馨提示:
为了更好的体验,请点击原文链接进行浏览
摘录时间:
2020-08-20 14:49:48
JSON解读_20191130223712.png

第一步,创建从网络获取数据的Function:

'-----------------------------------------------
'获取网络Json数据(测试成功)
'-----------------------------------------------
Function getWebData(ByVal URL As String, Optional ByVal Method As String = "GET", Optional ByVal ReturnType As String = "Text", Optional ByVal Async As Boolean = False, Optional ByVal Username As String = "", Optional ByVal Password As String = "")
    
    '处理变量
    Method = IIf(UCase(Method) = "GET", "GET", "POST")
    
    '创建对象
    Dim xmlHttp As Object
    Set xmlHttp = CreateObject("MSXML2.XMLHTTP")
    'Set xmlHttp = CreateObject("Msxml2.ServerXMLHTTP")
    
    '发送请求
    xmlHttp.Open Method, URL, Async, Username, Password
    xmlHttp.Send
    
    '等待响应
    Do While xmlHttp.ReadyState <> 4
        DoEvents
    Loop
    
    '得到请求数据
    If xmlHttp.ReadyState = 4 Then
    
        '根据要求返回不同结果
        Select Case UCase(ReturnType)
            Case "TEXT"
                getWebData = xmlHttp.responsetext
            Case "BODY"
                getWebData = xmlHttp.responsebody
            Case "STREAM"
                getWebData = xmlHttp.responseStream
            Case "XML"
                getWebData = xmlHttp.responseXML
            Case Else
                getWebData = xmlHttp.responsetext
        End Select
        
    Else
        getWebData = "调用失败,错误代码:" & xmlHttp.Status    '返回错误结果
    End If
    
    '销毁对象
    Set xmlHttp = Nothing
    
End Function

第二步,获取数据并解析JSON:

'-------------------------------------------------------------
'解析JSON成功
'参考:http://club.excelhome.net/thread-1303169-2-1.html
'-------------------------------------------------------------
Public Sub getResource()
    
    '创建对象
    Dim oDom As Object
    Dim oWindow As Object
    Dim strHTML As String
    
    Set oDom = CreateObject("HTMLFILE")
    Set oWindow = oDom.parentWindow
    
    '{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"27.9","WD":"南风","WS":"小于3级","SD":"28%","AP":"1002hPa","njd":"暂无实况","WSE":"<3","time":"17:55","sm":"2.1","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB"}}
    strHTML = getWebData("http://www.weather.com.cn/data/sk/101010100.html", "get", "text")   
    
    '创建对象
    oWindow.execScript "a=" & strHTML
    
    Cells(1, 1) = strHTML
    Cells(2, 1) = oWindow.eval("a.weatherinfo.city")
    Cells(3, 1) = oWindow.eval("a.weatherinfo.cityid")
    Cells(4, 1) = oWindow.eval("a.weatherinfo.temp")
    Cells(5, 1) = oWindow.eval("a.weatherinfo.WD")
    Cells(6, 1) = oWindow.eval("a.weatherinfo.SD")
    
End Sub
php技术微信