[英]Export Excel Data to Json dynamic Array with VBA
我在 excel 中有一些數據,我正在循環使用 VBA 以創建嵌套的 JSON 字符串。
ColumnF 包含值 a、b 和 c,分別位於第 1、2 和 3 行。
我正在使用以下代碼:
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 加載這樣的數組? 任何幫助表示贊賞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.