类型不匹配错误(Array):解析VBA中的JSON字符串数组

时间:2016-09-01 12:23:56

标签: json vba type-mismatch

我一直收到“类型不匹配错误”(表示它不是数组?):

Sub FillTaxiInfo

For i = 0 To UBound(data("prices")) - 1

代码试图解析JSON(参见下面的“价格”):

{"id":1,"prices":[{"name":"expressTaxi","fare":{"fareType":"standard", "base":"$2.50"...}}

当我放置断点并检查“价格”时,它告诉我“值”是表达式未在上下文中定义且“类型”为空。

非常感谢任何其他改进建议。

我的完整代码:

Option Explicit

Sub Run()

Dim myUrls As Variant
myUrls = Array("URL1, URL2, URL3")
FillMultipleCityInfo myUrls, ActiveWorkbook

End Sub

Function GetJson(ByVal url As String) As Dictionary
With New WinHttpRequest
    .Open "GET", url
    .Send
    Set GetJson = JsonConverter.ParseJson(.ResponseText)
End With
End Function

Sub FillTaxiInfo(data As Dictionary, sheet As Worksheet)
Dim i As Integer, taxi As Dictionary
For i = 0 To UBound(data("prices")) - 1
    Set taxi = data("prices")(i)
    If taxi.Exists("name") Then
      sheet.Cells(i, 1) = taxi("name")
      sheet.Cells(i, 2) = taxi("fare")("fareType")
    End If
Next i
End Sub

Sub FillMultipleCityInfo(urls As Variant, book As Workbook)
Dim i As Integer, data As Dictionary, sheet As Worksheet

For i = 0 To UBound(urls) - 1
    Set data = GetJson(urls(i))
    Set sheet = book.Sheets(i + 1)
    FillTaxiInfo data, sheet
Next i
End Sub

1 个答案:

答案 0 :(得分:1)

您正在尝试接收字典数据结构的UBound()而不是数组。 UBound()只能在数组上运行。

相反,您似乎想要迭代字典的键。这是一个如何做到这一点的小例子。

Public Sub Dict_Iter()
    Dim key As Variant 'Even though the key is a string --
                       'Objects/Variant are needed in a For Each Loop
    Dim dict As New Dictionary

    'Add several items to the dictionary
    With dict
        .Add "a", "a"
        .Add "b", "b"
        .Add "c", "c"
    End With

    'Iterate over the keys
    For Each key In dict.Keys()
       Debug.Print dict(key)
    Next
End Sub