gpt4 book ai didi

JSON VBA 解析到 Excel

转载 作者:行者123 更新时间:2023-12-02 14:24:34 24 4
gpt4 key购买 nike

我进行了一些 JSON 解析工作。我使用 VBA 从网络服务器解析 JSON 代码,将其写入 Excel 工作表的单元格 A1。但我无法将其转换为其他单元格。

这是我的 JSON 示例:

{
"@type":["IN.areaList.1","OII.list.1"],
"@self":"/bereiche",
"list":[
{"@type":["IN.bereich.1"],
"@self":"/1.1.Bereich.2.7",
"scha":false,
"trlState":"",
"oiischa":false,
"readyTo1":false,
"readyTo2":false,
"numberOfBypassedDevices":0,
"test":"",
"TestActive":false,
"chModeActive":false,
"incs":[]}
]
}

这是我的子程序,它正在用于另一个示例:

Sub JsonToExcelExample()

Dim jsonText As String
Dim jsonObject As Object
Dim item As Object
Dim i As Long
Dim ws As Worksheet

Set ws = Worksheets("Remote")
jsonText = ws.Cells(1, 1)
Set jsonObject = JsonConverter.ParseJson(jsonText)
i = 3
ws.Cells(2, 1) = "Color"
ws.Cells(2, 2) = "Hex Code"
For Each item In jsonObject("0")
ws.Cells(i, 1) = item("color")
ws.Cells(i, 2) = item("value")
i = i + 1
Next

End Sub

应如何更改此 VBA 代码,以便将上述 JSON 示例像表格一样放置在工作表上?

最佳答案

看一下下面的例子。 导入JSON.bas模块到 VBA 项目中进行 JSON 处理。

Option Explicit

Sub Test()

Dim sJSONString As String
Dim vJSON
Dim sState As String
Dim aData()
Dim aHeader()
Dim vResult

' Retrieve question #50068973 HTML content
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://stackoverflow.com/questions/50068973", False
.send
sJSONString = .responseText
End With
' Extract JSON sample from the question
sJSONString = "{" & Split(sJSONString, "<code>{", 2)(1)
sJSONString = Split(sJSONString, "</code>", 2)(0)
' Parse JSON sample
JSON.Parse sJSONString, vJSON, sState
If sState = "Error" Then
MsgBox "Invalid JSON"
End
End If
' Convert raw JSON to array and output to worksheet #1
JSON.ToArray vJSON, aData, aHeader
With Sheets(1)
.Cells.Delete
.Cells.WrapText = False
OutputArray .Cells(1, 1), aHeader
Output2DArray .Cells(2, 1), aData
.Columns.AutoFit
End With
' Flatten JSON
JSON.Flatten vJSON, vResult
' Convert flattened JSON to array and output to worksheet #2
JSON.ToArray vResult, aData, aHeader
With Sheets(2)
.Cells.Delete
.Cells.WrapText = False
OutputArray .Cells(1, 1), aHeader
Output2DArray .Cells(2, 1), aData
.Columns.AutoFit
End With
MsgBox "Completed"

End Sub

Sub OutputArray(oDstRng As Range, aCells As Variant)

With oDstRng
.Parent.Select
With .Resize(1, UBound(aCells) - LBound(aCells) + 1)
.NumberFormat = "@"
.Value = aCells
End With
End With

End Sub

Sub Output2DArray(oDstRng As Range, aCells As Variant)

With oDstRng
.Parent.Select
With .Resize( _
UBound(aCells, 1) - LBound(aCells, 1) + 1, _
UBound(aCells, 2) - LBound(aCells, 2) + 1)
.NumberFormat = "@"
.Value = aCells
End With
End With

End Sub

您提供的原始样本的工作表#1 上的输出如下:

raw

工作表 #2 上有展平的示例输出:

flattened

顺便说一句,应用了类似的方法 in other answers .

关于JSON VBA 解析到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50068973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com