VBA宏,类型不匹配错误

时间:2017-12-10 02:32:05

标签: excel vba excel-vba

我试图在excel中获取JSON数据并解析它。但是,我收到错误:输入错误。

有谁知道如何解决这个问题?我无法弄清楚我做错了什么。

这是我使用的https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD

指向API的链接

以下是代码:

Public Sub exceljson()

    Dim https As Object, JSON As Object, i As Integer

    Set https = CreateObject("MSXML2.XMLHTTP")

    https.Open "GET", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD", False
    https.Send

    Set JSON = ParseJson(https.responseText)
    i = 2

    For Each Item In JSON
        Sheets(1).Cells(i, 1).Value = Item("USD")
        i = i + 1
    Next

    MsgBox ("complete")

End Sub

1 个答案:

答案 0 :(得分:1)

如果您确认已正确导入JsonConverter模块和Dictionary类并参考Microsoft Scripting Runtime,则以下代码将有效:

    Public Sub exceljson()
    Dim https As Object, Json As Object, i As Integer

    Dim Item As Variant

    Set https = CreateObject("MSXML2.XMLHTTP")
    https.Open "GET", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD", False
    https.Send

    Set Json = JsonConverter.ParseJson(https.responseText)

    i = 2
    For Each Item In Json.Items
        Sheets(1).Cells(i, 1).Value = Item
        i = i + 1
    Next
    MsgBox ("complete")
End Sub

希望它有所帮助!

更新

您应该分析服务器响应的Json数据," Data"是一本字典。因此,您应该在For Each Loop中使用词典。

以下代码将获取所有数据,我只使用" high"关键作为例子。您可以轻松地将其他键输出到Excel中。

Public Sub exceljson()
    Dim https As Object, Json As Object, DataItem As Dictionary, i As Integer


    Set https = CreateObject("MSXML2.XMLHTTP")
    https.Open "GET", "https://min-api.cryptocompare.com/data/histominute?fsym=BTC&tsym=USD&limit=60&aggregate=3&e=CCCAGG", False
    https.Send

    'Use this debug command to see the whole response text
    'Debug.Print https.responseText
    Set Json = JsonConverter.ParseJson(https.responseText)


    i = 2
    For Each DataItem In Json("Data")
        'Use "high" as example, you can output other key/values
        Sheets(1).Cells(i, 1).Value = DataItem("high")

        i = i + 1
    Next
    MsgBox ("complete")
End Sub