【问题标题】:Type Mismatch Error (Array): parsing JSON array of strings in VBA类型不匹配错误(数组):在 VBA 中解析字符串的 JSON 数组
【发布时间】:2016-09-01 12:23:55
【问题描述】:

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

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

【问题讨论】:

    标签: json vba type-mismatch


    【解决方案1】:

    您正在尝试接收 Dictionary 数据结构而不是数组的 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
    

    【讨论】:

    • “a”、“a”让我感到困惑——因为它几乎看起来像一个键值对。举一个具体的例子,我会使用:.Add "prices", "names" 两者都是键,“名称”的级别/索引低于“价格”?此外,在我尝试将这些值分配给单元格时,我将简单地将底部迭代构造为:sheet.Cells(i, 1) = Debug.Print dict(key) 在初始化 i 并在 i+1 中分层?
    • "a", "a" 实际上是一个键值对,因为这是 Dictionary 数据类型所必需的。键是唯一元素,而值是找到匹配键时返回的值。同样,不确定您的特定程序需要做什么,但我想我回答了"type mismatch error" (indicating that its not an array?) 提出的问题
    • 知道了,我会检查答案,但不幸的是,静态值解决方案对我不起作用。我正在从网络上抓取 JSON,它具有静态键,但值是可变/未知的。
    猜你喜欢
    • 2013-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2017-09-05
    • 2021-02-19
    相关资源
    最近更新 更多