[英]Export Excel Data to Json dynamic Array with VBA
I have some data in excel that I am looping through with VBA in order to create a nested JSON string.我在 excel 中有一些数据,我正在循环使用 VBA 以创建嵌套的 JSON 字符串。
ColumnF contains values a, b and c, in row 1, 2 and 3 respectively. ColumnF 包含值 a、b 和 c,分别位于第 1、2 和 3 行。
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? rulesContainer("ColumnF") = Array(Cells(1, 6), Cells(2, 6), Cells(3, 6))
以加载内部可能包含不同数量对象的动态数组? 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 [ "?", "?", "?", "?", "?", "?"换句话说,由于我在数组中可能有可变数量的对象(不仅仅是[“a”,“b”,“c”]),是否可以加载数组以使其变为动态[“?” , "?", "?", "?", "?", "?" ]?
]? How can we load such array using VBA?
我们如何使用 VBA 加载这样的数组? Any help appreciated.
任何帮助表示赞赏。
The trick is to use WorksheetFunction.Transpose()
to convert the range values from 2 dimensional array that has only 1 column to 1 dimensional array.诀窍是使用
WorksheetFunction.Transpose()
将范围值从只有 1 列的二维数组转换为一维数组。
rulesContainer("ColumnF") = WorksheetFunction.Transpose(Range("F1", Cells(Rows.Count, "F").End(xlUp)).Value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.