我需要创建一个访问REST API的程序,并将JSON响应导入Excel。我正在使用XMLHTTP WebRequest将响应转换为字符串,然后使用VBA-JSON库来解析它。
示例代码:
Dim Url As String
Dim Response As String
Dim HttpReq, ResponseObj As Object
Url = "https://jsonplaceholder.typicode.com/posts"
'Download JSON response and Parse it into an object
Set HttpReq = CreateObject("WinHttp.WinHttprequest.5.1")
HttpReq.SetTimeouts -1, -1, -1, -1
HttpReq.Open "GET", Url, False
HttpReq.Send
Response = HttpReq.ResponseText 'Line with Out of Memory Error
ResponseObj = ParseJson(Response)
'This is followed by further code that places the response rows into Excel Cells
输入是结构良好的数组,类似于此处使用的URL,当前代码适用于大多数请求。但是有些请求的响应大约为40 MB,我在检索响应时出现“Out of Memory”错误(引用HttpReq.ResponseText
的行)。我尝试重新启动机器,关闭其他程序,Excel安全模式等,但错误仍然存在。
我的问题是,有没有什么方法可以下载,解析并以更高效的内存方式将数据导入Excel,这样我就不会遇到上面的内存错误。作为参考,我需要使用Excel 2010 32位,因为这是我工作场所唯一批准和安装的版本。
答案 0 :(得分:1)
尝试以下方法从该网页获取Id
,Title
和body
。
Sub Get_data()
Dim HTTP As New XMLHTTP60, res As Variant
Dim r As Long, v As Long
With HTTP
.Open "GET", "https://jsonplaceholder.typicode.com/posts", False
.setRequestHeader "User-Agent", "Mozilla/5.0"
.send
res = Split(.responseText, "id"":")
End With
r = UBound(res)
For v = 1 To r
Cells(v, 1) = Split(res(v), ",")(0)
Cells(v, 2) = Split(Split(Split(res(v), "title"":")(1), """")(1), """,")(0)
Cells(v, 3) = Split(Split(Split(res(v), "body"":")(1), """")(1), """,")(0)
Next v
End Sub
参考添加到库:
Microsoft XML, V6.0