I have some data in excel that I am looping through with VBA in order to create a nested JSON string.
ColumnF contains values a, b and c, in row 1, 2 and 3 respectively.
I am using the following code:
Public Sub Excel_to_json()
Dim mainContainer As New Dictionary, rulesArray As New Collection, rulesContainer As New Dictionary
Dim excelRange As Range
Set excelRange = Cells(1, 1).CurrentRegion
mainContainer("ColumnA") = Cells(1, 1)
mainContainer("ColumnB") = Cells(1, 2)
mainContainer("ColumnC") = Cells(1, 3)
mainContainer("ColumnD") = Cells(1, 4)
rulesContainer("ColumnE") = Cells(1, 5)
rulesContainer("ColumnF") = Array(Cells(1, 6), Cells(2, 6), Cells(3, 6))
rulesContainer("ColumnG") = Cells(1, 7)
rulesContainer("ColumnH") = Cells(1, 8)
rulesContainer("ColumnI") = Cells(1, 9)
rulesContainer("ColumnJ") = Cells(1, 10)
rulesContainer("ColumnK") = Cells(1, 11)
rulesContainer("ColumnL") = Cells(1, 12)
rulesContainer("ColumnM") = Cells(1, 13)
rulesContainer("ColumnN") = Cells(1, 14)
rulesArray.Add rulesContainer
mainContainer.Add "rules", rulesArray
Debug.Print ConvertToJson(mainContainer, Whitespace:=2)
End Sub
I get the results I want, namely:
{
"ColumnA": 1,
"ColumnB": 2,
"ColumnC": 3,
"ColumnD": 4,
"rules": [
{
"ColumnE": 5,
"ColumnF": [
"a",
"b",
"c"
],
"ColumnG": 7,
"ColumnH": 8,
"ColumnI": 9,
"ColumnJ": 10,
"ColumnK": 11,
"ColumnL": 12,
"ColumnM": 13,
"ColumnN": 14
}
]
}
My question is rather how I replace the following piece of code:
rulesContainer("ColumnF") = Array(Cells(1, 6), Cells(2, 6), Cells(3, 6))
in order to load a dynamic array which could have a different number of objects inside? In order words, since I might have a variable number of objects inside the array (not just [ "a", "b", "c" ]), is it possible to load the array so that it becomes dynamic [ "?", "?", "?", "?", "?", "?" ]? How can we load such array using VBA? Any help appreciated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.