如何在Excel表

时间:2018-01-09 14:15:14

标签: excel api store record ticker

我没有VBA经验所以我希望有一种方法可以在不使用宏或编程的情况下执行此操作 - 如果没有帮助代码并解释它正在做什么,那么我可以从中学习,非常感谢。 :)

我正在使用每日更新的API自动收录器,它会给我一个日期和值。

然后我有一个预定年份的表,01/01/18> 31/12/18(例如),与值的单元格相邻。

我已经使用vlookup来填充给定日期的值,但显然在当前状态下,数据不可记录,因此当API上的日期从01/01/18更改为02/01/18该值将丢失,并移动到下一个要填充的指定单元格。

有没有办法记录/存储这些数据 - 让它自动外部?没有手动复制/粘贴文本或值?

Mock up table for example

1 个答案:

答案 0 :(得分:0)

您从该API获取的数据是JSON。不幸的是,VBA中对JSON的支持是100%不存在的。有些人已经创建了一些库,但由于你是VBA的新手,并且JSON响应非常小,我认为最好将API中的响应视为字符串并获取内容我们需要解析字符串。

该URL的示例(附加到Sheet1列A,B,C和D的任何内容:

Sub getTickerValue()

    'Get the data from the API
    Dim strResponse As String: strResponse = LoadHTML("https://api.fixer.io/latest?symbols=USD,GBP")

    'Since we aren't actually going to parse the json because it's not well supported in VBA
    '   we will instead remove everything we don't care about and parse the results
    '   So replace out double quotes and squirrely braces (Not a great idea for more complex json)
    strResponse = Replace(strResponse, Chr(34), "")
    strResponse = Replace(strResponse, "}", "")
    strResponse = Replace(strResponse, "{", "")

    'Load up each item into an array splitting on comma
    Dim jsonArray As Variant: jsonArray = Split(strResponse, ",")

    'Loop the array, sniff for the data we want, and toss it in it's respective variable
    Dim strBase As String, strDate As String, strRate1 As String, strRate2 As String
    For Each elem In jsonArray
        If Split(elem, ":")(0) = "base" Then strBase = Split(elem, ":")(1)
        If Split(elem, ":")(0) = "date" Then strDate = Split(elem, ":")(1)
        If Split(elem, ":")(0) = "rates" Then strRate1 = Split(elem, ":")(2)
        If Split(elem, ":")(0) = "USD" Then strRate2 = Split(elem, ":")(1)
    Next elem

    'Set up the range where we will output this by starting at cell A99999
    '   in Sheet1 and going up until we hit the first occupied cell
    '   offset by 1 row to get the first unoccupied cell
    Dim outRange As Range
    Set outRange = Sheet1.Range("A99999").End(xlUp).Offset(1)

    'Now we know the last unoccupied cell in Sheet1, go ahead and dump the data
    outRange.Value = strBase
    outRange.Offset(, 1).Value = strDate
    outRange.Offset(, 2).Value = strRate1
    outRange.Offset(, 3).Value = strRate2


End Sub

Function LoadHTML(xmlurl) As String
  'Using the XMLHTTP library to get the results since monkeying with IE is ugly and painful
  Dim xmlhttp

  Set xmlhttp = CreateObject("MSXML2.XMLHTTP")
  xmlhttp.Open "GET", xmlurl, False

  ' switch to manual error handling
  On Error Resume Next

  xmlhttp.Send
  If Err.Number <> 0 Then
    WScript.Echo xmlhttp.parseError.Reason
    Err.Clear
  End If

  ' switch back to automatic error handling
  On Error GoTo 0

  LoadHTML = xmlhttp.responseText
End Function

这并不是你想要的,但我认为它足够接近让你进入大球场。您可以通过在工作表上创建一个按钮或形状然后将其指向&#34; GetTickerValue&#34;来运行它。宏。或者在将其粘贴到新的VBA模块后,您可以将光标放在GetTicketValue代码块中,然后点击顶部的播放按钮(或F5)。它将获取数据并将其附加到Sheet1的任何内容中。