简体   繁体   中英

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.

ColumnF contains values a, b and c, in row 1, 2 and 3 respectively.

Excel 表在这里

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 trick is to use WorksheetFunction.Transpose() to convert the range values from 2 dimensional array that has only 1 column to 1 dimensional array.

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

即时窗口

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM