San*_*osh 15 excel vba json xmlhttprequest excel-vba
我需要处理一个JSON对象,它是Excel VBA中XMLHTTPRequest的响应.我写了下面的代码,但它不起作用:
  Dim sc As Object
  Set sc = CreateObject("ScriptControl")
  sc.Language = "JScript"
  Dim strURL As String: strURL = "blah blah"
  Dim strRequest
  Dim XMLhttp: Set XMLhttp = CreateObject("msxml2.xmlhttp")
  Dim response As String
  XMLhttp.Open "POST", strURL, False
  XMLhttp.setrequestheader "Content-Type", "application/x-www-form-urlencoded"
  XMLhttp.send strRequest
  response = XMLhttp.responseText
  sc.Eval ("JSON.parse('" + response + "')")
我收到错误运行时错误'429'ActiveX组件无法在行中   创建对象Set sc = CreateObject("ScriptControl")
解析JSON对象后,如何访问JSON对象的值?
PS My JSON对象示例: {"Success":true,"Message":"Blah blah"}
San*_*osh 12
代码从nseindia站点获取数据,该数据作为responseDiv元素中的JSON字符串.
必需的参考文献

我用过的3类模块
(我从这里选择了这些课程模块)
您可以从此链接下载该文件
标准模块
Const URl As String = "http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol=ICICIBANK"
Sub xmlHttp()
    Dim xmlHttp As Object
    Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
    xmlHttp.Open "GET", URl & "&rnd=" & WorksheetFunction.RandBetween(1, 99), False
    xmlHttp.setRequestHeader "Content-Type", "text/xml"
    xmlHttp.send
    Dim html As MSHTML.HTMLDocument
    Set html = New MSHTML.HTMLDocument
    html.body.innerHTML = xmlHttp.ResponseText
    Dim divData As Object
    Set divData = html.getElementById("responseDiv")
    '?divData.innerHTML
    ' Here you will get a string which is a JSON data
    Dim strDiv As String, startVal As Long, endVal As Long
    strDiv = divData.innerHTML
    startVal = InStr(1, strDiv, "data", vbTextCompare)
    endVal = InStr(startVal, strDiv, "]", vbTextCompare)
    strDiv = "{" & Mid(strDiv, startVal - 1, (endVal - startVal) + 2) & "}"
    Dim JSON As New JSON
    Dim p As Object
    Set p = JSON.parse(strDiv)
    i = 1
    For Each item In p("data")(1)
       Cells(i, 1) = item
       Cells(i, 2) = p("data")(1)(item)
        i = i + 1
    Next
 End Sub
我在以下库中获得了很多成功:
https://github.com/VBA-tools/VBA-JSON
该库Scripting.Dictionary用于Objects和Collectionfor Arrays,我对解析相当复杂的json文件没有任何问题.
至于自己解析json的更多信息,请查看此问题,了解有关sc.Eval调用返回的JScriptTypeInfo对象问题的一些背景信息:
最后,对于一些有用的类XMLHTTPRequest,我的项目的一个小插件,VBA-Web:
https://github.com/VBA-tools/VBA-Web
| 归档时间: | 
 | 
| 查看次数: | 67237 次 | 
| 最近记录: |