如何使用VBA从网址导入json数据?

Chr*_*ris 4 excel ms-access vba json http

我有以下json数组,您可以在下面的URL轻松访问:

https://crowdfluttr.firebaseio.com/test/array.json

它具有以下输出:

{"-0p":{"date":"2015-01-01","string":"apple","value":1},"-1p":{"date":"2015-02-04","string":"banana","value":50},"-2p":{"date":"2015-02-03","string":"carrot","value":99},"-3p":{"date":"2015-02-02","string":"banana","value":20},"-4p":{"date":"2015-03-01","string":"banana","value":11},"-5p":{"date":"2015-04-01","string":"kiwi","value":23},"-6p":{"date":"2015-05-01","strawberry":"banana","value":10}}
Run Code Online (Sandbox Code Playgroud)

我想从此URL中提取此json数据,然后解析它以推送到Microsoft Access。

我找到了说明如何解析JSON的资源(解析JSON在Excel VBA中解析JSON),但没有从URL中提取它然后进行解析

Axe*_*ter 5

I would use XMLHTTP to download the JSON.

For parsing JSON with VBA see https://github.com/VBA-tools/VBA-JSON.

Download the ZIP file. Extract the JsonConverter.bas. Open Excel and the VBA-editor with your VBA-project. Right click the VBA-project in Project Explorer and click Import File.... Browse to the JsonConverter.bas file and import it. Make sure, you have included a reference to "Microsoft Scripting Runtime" via Tools-References.

Example using your URL:

Sub test()

 Dim httpObject As Object
 Set httpObject = CreateObject("MSXML2.XMLHTTP")

 sURL = "https://crowdfluttr.firebaseio.com/test/array.json"

 sRequest = sURL
 httpObject.Open "GET", sRequest, False
 httpObject.send
 sGetResult = httpObject.responseText

 MsgBox sGetResult

 Dim oJSON As Object
 Set oJSON = JsonConverter.ParseJson(sGetResult)

 For Each sItem In oJSON
  dItemDate = oJSON(sItem)("date")
  sItemString = oJSON(sItem)("string")
  vItemValue = oJSON(sItem)("value")

  MsgBox "Item: " & sItem & " Date: " & dItemDate & " String: " & sItemString & " Value: " & vItemValue
 Next

End Sub
Run Code Online (Sandbox Code Playgroud)

This code will work for your sample JSON like:

{"-0p":{"date":"2015-01-01","string":"apple","value":1},"-1p":{"date":"2015-02-04","string":"banana","value":50}, ... }

You will have to analyze the JSON you get from httpObject.responseText to adapt the code for getting values from other JSON structures.