如何从使用VBA的URL导入json数据?

我有以下的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}} 

我想拉这个JSON数据从这个url,然后parsing它推入微软访问。

我发现资源解释如何parsingJSON( parsingJSON , 在Excel VBA中parsingJSON ),但不从URL中拉出来,然后parseit

我会使用XMLHTTP来下载JSON。

有关使用VBAparsingJSON,请参阅https://github.com/VBA-tools/VBA-JSON

下载ZIP文件。 提取JsonConverter.bas 。 用你的VBA项目打开Excel和VBA编辑器。 右键单击项目资源pipe理器中的VBA项目,然后单击Import File....浏览到JsonConverter.bas文件并导入它。 确保您通过Tools-References包含了对“Microsoft脚本运行时” Tools-References

使用您的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 

这段代码将适用于您的示例JSON如:

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

你将不得不分析你从httpObject.responseText得到的JSON ,以适应从其他JSON结构获取值的代码。

您可以在这里学习答案,然后查找VBA.CVRAPI ,其中包含所有必需的Json模块以从URL中检索数据。 尽pipe为其他目的而创build,但Json模块是通用的,可以很容易地重复使用。

包含的演示表单演示了这一点。 您应该能够将其采用到您的url进行testing。