문제 설명
Excel VBA의 세로 열에 여러 json을 생성하는 방법은 무엇입니까? (How to generate multiple json in vertical column in Excel VBA?)
엑셀 매크로 사용 첫 번째 줄은 json 파일 이름이고 두 번째 열은 값입니다.
첫 번째 열을 json 객체의 키로 사용하여 두 번째 열의 값만 세 번째 열의 값만 생성합니다.
어떻게 생성합니까? Excel과 동일한 디렉토리에 json을 각각 일괄적으로?
예를 들어, B열은 A열의 값을 키로, B열의 값은 b1.json입니다. C열은 A열의 값을 키로 사용하고 C열과 c1.json의 값을 사용합니다.
예를 들어, 완성된 json에 C열까지 설명이 있는 경우
b1.json
[{
a2: b2,
a3: b3,
a4: b4,
}]
c1.json
[{
a2: c2,
a3: c3,
a4: c4,
}]
생성을 원합니다.<
참조 솔루션
방법 1:
Here is VBA example showing how the files could be created. Import JSON.bas module from VBA JSON parser into the VBA project for JSON processing, and include a reference to "Microsoft Scripting Runtime" (take a look here how to import module and add reference).
Put the below code in a standard module:
Option Explicit
Sub test()
With ActiveSheet.Cells(1, 1).CurrentRegion
If .Cells.Count < 4 Then
MsgBox "No data"
Exit Sub
End If
Dim source
source = .Value
End With
Dim i
For i = 2 To UBound(source, 2)
Dim data
Set data = New Dictionary
Dim j
For j = 2 To UBound(source, 1)
data(source(j, 1)) = source(j, i)
Next
saveTextToFile _
JSON.Serialize(Array(data)), _
ThisWorkbook.path & "\" & source(1, i) & ".json", _
"UTF‑8"
Next
MsgBox "Completed"
End Sub
Sub saveTextToFile(content, filePath, charset)
With CreateObject("ADODB.Stream")
.Type = 2 ' adTypeText
.Open
.charset = charset
.WriteText content
.Position = 0
.Type = 1 ' TypeBinary
.SaveToFile filePath, 2
.Close
End With
End Sub
The source data I tested code with:
The output is as follows:
file1.json
[
{
"prop1": "Alice",
"prop2": "Bob",
"prop3": "Charlie",
"prop4": "Eve",
"prop5": "Dan"
}
]
file2.json
[
{
"prop1": "Tomatoes",
"prop2": "Bananas",
"prop3": "Watermelons",
"prop4": "Apples",
"prop5": "Grapefruit"
}
]
file3.json
[
{
"prop1": "Russia",
"prop2": "Canada",
"prop3": "USA",
"prop4": "China",
"prop5": "Brazil"
}
]
BTW, the similar approach applied in other answers.
방법 2:
This is the exact problem I'm having but I can't seem to import the JSON.bas file. It throws an error saying the file is too complex.
(by project sixth、omegastripes、Paolo Valente)