使用VBA写入部分数据

时间:2018-08-29 15:20:02

标签: json excel 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;"
    }
  }
}

1 个答案:

答案 0 :(得分:1)

如果它是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