使用VBA将Excel数据导出到Json动态数组中

问题描述 投票:0回答:1

我在Excel中有一些数据,我正在使用VBA进行循环以创建嵌套的JSON字符串。

ColumnF分别在第1、2和3行中包含值a,b和c。

Excel Tabel here

我正在使用以下代码:

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加载此类数组?任何帮助表示赞赏。

arrays json excel vba dynamic
1个回答
0
投票

技巧是使用WorksheetFunction.Transpose()将范围值从只有1列的2维数组转换为1维数组。

 rulesContainer("ColumnF") = WorksheetFunction.Transpose(Range("F1", Cells(Rows.Count, "F").End(xlUp)).Value)

Immediate Window

© www.soinside.com 2019 - 2024. All rights reserved.