【发布时间】:2016-02-11 19:28:57
【问题描述】:
我正在使用 Excel 宏从 Yahoo Finance 检索 CSV 文件。在 A 列中,我将股票代码列为输入。我曾经运行一个宏,将每个代码插入 URL,然后将结果输出到 B 列。然后我会调用一个函数将 B 列中的文本拆分为 B 列到 E 列。
当我创建一个连接的 URL 字符串并只调用一次 URL 时,该函数变得更快。主要问题是我收到以下格式的数据:
"81.950,342.05B,"Exxon Mobil Corporation Common ",263.71B
81.38,201.29B,"Alibaba Group Holding Limited A",13.56B
754.77,519.78B,"Alphabet Inc.",71.76B
120.57,649.30B,"Apple Inc.",233.72B"
当我一次调用一个 URL 时,我可以使用 Text to Columns 函数分离出必要的数据。现在我需要它按列和行分隔。
Sub StockDataPull()
Dim url As String
Dim http As Object
Dim LastRow As Long
Dim Symbol_rng As Range
Dim Output_rng As Range
'Define Last Row in Ticker Range
With ActiveSheet
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
Application.ScreenUpdating = False
Set Symbol_rng = Range("A5:A" & LastRow).Cells
Set Output_rng = Range("C5:F" & LastRow).Cells
'Open Yahoo Finance URL
url = "http://download.finance.yahoo.com/d/quotes.csv?s=" & concatRange(Symbol_rng) & "&f=pj1ns6"
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", url, False
http.Send
Output_rng = http.responseText
Set http = Nothing
Application.DisplayAlerts = False
Application.ScreenUpdating = True
End Sub
'The code below is what I used before Sub StockDataPull(). This code calls a URL for each ticker, instead of one URL for all tickers in a concatenated string. It's considerably slower, but it works because it outputs the data two cells away from the ticker, then I call Sub Delimiter() to separate it across the next few consecutive columns.
Sub StockData()
Dim url As String
Dim http As Object
Dim LastRow As Long
Dim Symbol_rng As Range
''Define Last Row in Ticker Range
With ActiveSheet
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
Application.ScreenUpdating = False
Set Symbol_rng = Range("A5:A" & LastRow).Cells
For Each cell In Symbol_rng
''Open Yahoo Finance URL
url = "http://download.finance.yahoo.com/d/quotes.csv?s=" & cell.Value & "&f=pj1ns6"
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", url, False
http.Send
cell.Offset(rowOffset:=0, columnOffset:=2) = http.responseText
Set http = Nothing
Next cell
Application.DisplayAlerts = False
Application.ScreenUpdating = True
Call Delimiter
End Sub
Sub Delimiter()
''Define Last Row in Ticker Range
With ActiveSheet
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
''Separate the data into four columns
Range("C5:C" & LastRow).TextToColumns Destination:=Range("C5"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1)), TrailingMinusNumbers:=True
''Unwrap the text
Range("C5:F" & LastRow).Select
With Selection
.WrapText = False
End With
End Sub
【问题讨论】:
-
哪里出了问题?
-
您还可以发布预期输出的示例表吗?不过好像@GSazheniuk 有气味了,看
Split。 -
谢谢,我确实看过拆分功能。我可以使用它将输出数据分成列;我只是不知道如何将它放入行中。
-
如果有代码可以分栏,可以发一下吗?应该只需要稍微调整一下就可以放入行中。