首页 > 解决方案 > 使用 VBA 写入部分数据

问题描述

我有一个很大的 JSON 文件,但我需要的信息只是其中的一小部分。有什么方法可以提取我想要的部分并写入 Excel 工作表而不是写入整个文件?请看下面的例子。我只想提取“文本”部分

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
  }
}

标签: jsonexcelvba

解决方案


如果它是一个 JSON 文件,您可以阅读如下内容并将其清空到工作表中

Option Explicit
Public Sub GetInfo()
    Dim strJSON As String, json As Object, rowNumber As Long
    Application.ScreenUpdating = False
    Const PATH As String = "C:\Users\User\Desktop\test.JSON"
    strJSON = GetJSONFromFile(PATH)
    Set json = JsonConverter.ParseJson(strJSON)
    Set json = json("widget")("text")
    Dim key As Variant
    With ThisWorkbook.Worksheets("Sheet1")
        For Each key In json
            rowNumber = rowNumber + 1
            .Cells(rowNumber, 1) = key
            .Cells(rowNumber, 2) = json(key)
        Next key
    End With
    Application.ScreenUpdating = True
End Sub

Public Function GetJSONFromFile(ByVal PATH As String) As String
    Dim fso As Object, f As Object, outputString As String

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.OpenTextFile(PATH)

    Do Until f.AtEndOfStream
        outputString = f.ReadAll()
    Loop
    f.Close

    GetJSONFromFile = outputString
End Function

如果您检查 JSON,您可以看到顶级字典有一个"widget"可以访问内部字典的键。其中之一有钥匙"text";那是您所追求的,可以使用语法访问

Set json = json("widget")("text")


您可以将顶部的子代码缩短为:

Option Explicit
Public Sub GetInfo()
    Dim strJSON As String, json As Object, rowNumber As Long
    Application.ScreenUpdating = False
    Const PATH As String = "C:\Users\HarrisQ\Desktop\test.JSON"
    strJSON = GetJSONFromFile(PATH)
    Set json = JsonConverter.ParseJson(strJSON)
    Set json = json("widget")("text")
    With ThisWorkbook.Worksheets("Sheet1")
        .Cells(1, 1).Resize(json.Count) = Application.WorksheetFunction.Transpose(json.keys)
        .Cells(1, 2).Resize(json.Count) = Application.WorksheetFunction.Transpose(json.Items)
    End With
    Application.ScreenUpdating = True
End Sub

推荐阅读