0

我在 VBA 中使用 FIXER.IO 流行的 API 将汇率输入到我的工作表的某些单元格中,名为 USD、CNY、INR 等。Fixer.io API 返回一个文本格式,给出了我需要的汇率。自 2018 年 3 月 6 日起,旧版 Fixer API (api.fixer.io) 已弃用并更改为需要 API 访问密钥(在注册时获取)但仅返回 JSON 文件的新版本。如果我调用网址:

http://data.fixer.io/api/latest?access_key=XXXXXXXXXXXX&symbols=USD,CNY,INR,THB,SGD,AUD

我得到这个 JSON 作为回报:

{"success":true,"timestamp":1523343843,"base":"EUR","date":"2018-04-10","rates":{"USD":1.231986,"CNY":7.757563,"INR":79.980529,"THB":38.462602,"SGD":1.614924,"AUD":1.592345}}

如何解析我的 Excel 变量 (USD, CNY ...) 中的交换值?我试着环顾四周,但我非常有限的编程技能并没有帮助我适应任何解决方案。请给一个“假人”回复:)感谢您提供的任何帮助问候马可

4

1 回答 1

0

看看下面的例子。将 JSON.bas模块导入VBA 项目以进行 JSON 处理。

Option Explicit

Sub Test()

    Dim sJSONString As String
    Dim vJSON
    Dim sState As String
    Dim aData()
    Dim aHeader()

    ' Retrieve data
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://data.fixer.io/api/latest?access_key=209f86f5304e0043a0879d8cb45c9c10&symbols=USD,CNY,INR,THB,SGD,AUD", False
        .Send
        sJSONString = .ResponseText
    End With
    ' Parse JSON response
    JSON.Parse sJSONString, vJSON, sState
    ' Refer to target dictionary containing rates
    Set vJSON = vJSON("rates")
    ' Access to each item in dictionary
    Debug.Print vJSON("USD")
    Debug.Print vJSON("CNY")
    Debug.Print vJSON("INR")
    Debug.Print vJSON("THB")
    Debug.Print vJSON("SGD")
    Debug.Print vJSON("AUD")
    ' Convert to array and output to worksheet
    JSON.ToArray vJSON, aData, aHeader
    With Sheets(1)
        .Cells.Delete
        .Cells.WrapText = False
        OutputArray .Cells(1, 1), aHeader
        Output2DArray .Cells(2, 1), aData
        .Columns.AutoFit
    End With

End Sub

Sub OutputArray(oDstRng As Range, aCells As Variant)

    With oDstRng
        .Parent.Select
        With .Resize(1, UBound(aCells) - LBound(aCells) + 1)
            .NumberFormat = "@"
            .Value = aCells
        End With
    End With

End Sub

Sub Output2DArray(oDstRng As Range, aCells As Variant)

    With oDstRng
        .Parent.Select
        With .Resize( _
                UBound(aCells, 1) - LBound(aCells, 1) + 1, _
                UBound(aCells, 2) - LBound(aCells, 2) + 1)
            .NumberFormat = "@"
            .Value = aCells
        End With
    End With

End Sub

我的输出如下:

输出

工作表

顺便说一句,其他答案中应用的类似方法。

于 2018-04-11T08:48:54.277 回答