我在Excel中有一些数据,我正在使用VBA进行循环以创建嵌套的JSON字符串。
ColumnF分别在第1、2和3行中包含值a,b和c。
我正在使用以下代码:
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
我得到了想要的结果,即:
{
"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
}
]
}
我的问题是我如何替换下面的代码:
rulesContainer("ColumnF") = Array(Cells(1, 6), Cells(2, 6), Cells(3, 6))
为了加载一个动态数组,里面可能有不同数量的对象?顺便说一句,由于我在数组内部可能有可变数量的对象(而不仅仅是[“ a”,“ b”,“ c”]),是否可以加载数组以使其变为动态[“?” ,“?”,“?”,“?”,“?”,“?” ]?我们如何使用VBA加载此类数组?任何帮助表示赞赏。