Excel VBA – 如何从多个数组JSON中获取数据到列中

我发现了一个parsingJSON的解决scheme,并且对于这个例子来说工作的很好:

代码如下:

Sub Test() Dim jsonText As String Dim jsonObj As Dictionary Dim jsonRows As Collection Dim jsonRow As Collection Dim ws As Worksheet Dim currentRow As Long Dim startColumn As Long Dim i As Long Set ws = Worksheets("VIEW") 'Create a real JSON object jsonText = ws.Range("A1").Value 'Parse it Set jsonObj = JSON.parse(jsonText) 'Get the rows collection Set jsonRows = jsonObj("rows") 'Set the starting row where to put the values currentRow = 1 'First column where to put the values startColumn = 2 'B 'Loop through all the values received For Each jsonRow In jsonRows 'Now loop through all the items in this row For i = 1 To jsonRow.Count ws.Cells(currentRow, startColumn + i - 1).Value = jsonRow(i) Next i 'Increment the row to the next one currentRow = currentRow + 1 Next jsonRow End Sub 

和正在工作的JSON:

 {"rows":[["20120604", "ABC", "89"],["20120604", "BCD", "120"],["20120604", "CDE","239"]]} 

不过,我需要parsing具有这样的结构的JSON:

  [{"Id":"2604","Price": 520.4, "State": true},{"Id":"2605","Price": 322.8, "State": false},{"Id":"2619","Price": 104.7, "State": true},{"Id":"2628","Price": 182.2, "State": true}] 

这意味着,在这种情况下,它应该是3列(Id,价格,状态)和4行。

这应该很容易,但我只是一个新手在这里..

应该是这样的:

 Dim jsonRows As Collection Dim jsonRow As Dictionary '... 'Parse it Set jsonRows = JSON.parse(jsonText) 'Set the starting row where to put the values currentRow = 1 'First column where to put the values startColumn = 2 'B 'Loop through all the values received For Each jsonRow In jsonRows 'Now set all the values in this row ws.Cells(currentRow, startColumn).Value = jsonRow("Id") ws.Cells(currentRow, startColumn + 1).Value = jsonRow("Price") ws.Cells(currentRow, startColumn + 2).Value = jsonRow("State") 'Increment the row to the next one currentRow = currentRow + 1 Next jsonRow