首页 > 解决方案 > 将 JSON 解析为 Excel 但出现错误

问题描述

我一直在使用下面的代码将数据从 JSON 转换为 Excel,但 JSON 格式以下没有转换为 excel 并且Run time error: Invalid procedure call or argument在线出错ws.Cells(r, "C").Value = JSON("sku")

这是我一直在使用的代码。我不知道为什么当它适用于其他 JSON 格式而不是这种格式时会出现错误。

您的帮助将不胜感激。

    Dim objRequest  As Object
    Dim strUrl      As String
    Dim blnAsync    As Boolean
    Dim strResponse As String
    Dim idno        As Long
    Dim ws          As Worksheet
    Dim JSON        As Object
    Dim lrow As Long
    
    Set ws = Sheet4
    
    lrow = ws.Range("C" & ws.Rows.Count).End(xlUp).Row
    
    Set objRequest = CreateObject("MSXML2.XMLHTTP")
    strUrl = "url"
    blnAsync = True
    
    With objRequest
        .Open "GET", strUrl, blnAsync
        .setRequestHeader "Content-Type", "application/json"
        .send
        
        While objRequest.readyState <> 4
            DoEvents
        Wend
        
        strResponse = .ResponseText
    End With
    
    Set JSON = ParseJson(strResponse)
    
'    Debug.Print strResponse
            r = 2
            ws.Cells(r, "C").Value = JSON("sku")
            'r = r + 1

标签: jsonexcelvba

解决方案


我不确定 JSONConverter 中是否有此选项,但据我所知,它不喜欢解析以集合开头的 JSON 字符串,因此我通常会手动创建一个密钥,以便它能够正确转换。

下面的示例还显示了如何遍历集合并获取 的值sku

'.... Continue after you post the API...
    
    Dim strResponse As String
    strResponse = .responseText
    
    Dim resultDict As Object
    Set resultDict = ParseJson("{""result"":" & strResponse & "}")
    
    Dim i As Long
    Dim resultNum As Long
    resultNum = resultDict("result").Count
    
    For i = 1 To resultNum
        Debug.Print resultDict("result")(i)("id")
        Debug.Print resultDict("result")(i)("sku")
        Debug.Print resultDict("result")(i)("upc")
        

        'Loop through skuList collection
        Dim j As Long
        For j = 1 To resultDict("result")(i)("skuList").Count
            Debug.Print vbTab & resultDict("result")(i)("skuList")(j)("id")
            Debug.Print vbTab & resultDict("result")(i)("skuList")(j)("sku")
            Debug.Print vbTab & resultDict("result")(i)("skuList")(j)("skuTitle")
        Next j
    Next i

推荐阅读