使用 Excel VBA 从 CSV 文件中提取数据

Using Excel VBA to pull data from CSV file

我是 Yahoo Finance API 难民(他们停止了他们的 API 服务)试图切换到 Alpha Vantage。 我修改了之前用于 Yahoo Finance 的以下代码,但我在 Excel.

中收到 #VALUE 错误

下面的 URL 可以自行运行(如果您将其输入网络浏览器,它会打开一个 CSV),所以我想我真正的问题在于从 CSV 中提取正确的数据到我的 Excel 电子表格。有人能帮忙吗?

我正在尝试从 CSV 中提取第 2 行第 5 列(最后收盘价)中的数据。非常感谢!

Function StockClose(Ticker As String)

Dim URL As String, CSV As String, apikey As String, SCRows() As String, SCColumns() As String, pxClose As Double

apikey = "*censored*"

URL = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=" & Ticker & "&outputsize=full&" & apikey & "&datatype=csv"

Set xmlhttp = CreateObject("MSXML2.XMLHTTP")
    xmlhttp.Open "GET", URL, False
    xmlhttp.Send
    CSV = xmlhttp.responseText

    'split the CSV into rows
    SCRows() = Split(CSV, Chr(10))
    'split the relevant row into columns. 0 means 1st row, starting at index 0
    SCColumns() = Split(SCRows(1), ",")
    '6 means: 5th column; starting at index 0 - price close is in the 5th column
    pxClose = SCColumns(6)

    StockClose = pxClose

Set http = Nothing

End Function

如果我提取 json 而不是 csv:

则返回的数据示例

{ "Meta Data": { "1. Information": "Daily Prices (open, high, low, close) and Volumes", "2. Symbol": "SGD=X", "3. Last Refreshed": "2017-11-10", "4. Output Size": "Full size", "5. Time Zone": "US/Eastern" }, "Time Series (Daily)": { "2017-11-13": { "1. open": "1.3588", "2. high": "1.3612", "3. low": "1.3581", "4. close": "1.3587", "5. volume": "0" }, "2017-11-10": { "1. open": "1.3588", "2. high": "1.3612", "3. low": "1.3581", "4. close": "1.3587", "5. volume": "0" },

网站上的 "CSV" 选项是一个可下载的文件,而不是像这样解析的文本文档。一个更简单的解决方案是改用站点的 JSON 选项,它很容易加载到字符串中。

由于您只需要一个值,因此最简单的方法是只搜索字符串 "Close",然后 return 其后的值。

这是一个您可以根据需要进行调整的快速解决方案:

Option Explicit

Function StockClose(Ticker As String) As Double

    Dim URL As String, json As String, apiKey As String, xmlHTTP As Object
    Dim posStart As Integer, posEnd As Integer, strClose As String

    apiKey = "demo"
    URL = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=" & Ticker & "&outputsize=full&apikey=" & apikey 

    Set xmlHTTP = CreateObject("MSXML2.XMLHTTP")
    xmlHTTP.Open "GET", URL, False
    xmlHTTP.Send
    json = xmlHTTP.responseText
    Set xmlHTTP = Nothing

    posStart = InStr(json, "4. close") + 12
    posEnd = InStr(posStart, json, """") - 1
    strClose = Mid(json, posStart, posEnd - posStart)

    StockClose = Val(strClose)

End Function

Yahoo 结束了他们的 API 服务,这是一个悲伤的日子。尽管如此,还是有很多选择。您可以使用 Python 获取股票的时间序列数据。您也可以使用 R。我将留给您去弄清楚如何利用这些技术,因为您是 Excel-VBA 用户,如果您不想要这些选项,我不想强​​加给您。作为替代方案,请考虑下面列出的这两个选项之一。

http://finance.jasonstrimpel.com/bulk-stock-download/

http://investexcel.net/multiple-stock-quote-downloader-for-excel/

对于第二个 URL,单击标题为 'Get Excel Spreadsheet to Download Bulk Historical Stock Data from Google Finance' 的 link,您可以下载一个工具,它应该可以完成您想要的一切。