0

我是 VBA 的新手,我一生都无法解决这个问题。如果我没有使用正确的词语来描述我的问题,我深表歉意:

我在 VBA 中有一个函数,可以打开一个下载 csv 文件的 URL。我将分配给该下载的变量声明为“作为字符串”。然后,我将其拆分为行并将相关行(我需要第二行中的信息)拆分为列。我现在可以使用该功能在第二行的七列中的任何一列中显示任何信息,但一次只能显示一个。我还可以使用 Join() 方法在一个单元格中显示整个第二行,其中子字符串用逗号分隔。

目标:我希望能够自定义要显示的第二行中的哪些信息(子字符串),并且我希望它们显示在自己的相邻单元格中(按列相邻)。这可以通过使用数据功能区上的“文本到列”功能来完成,但我希望它在 Visual Basic 代码本身中进行转换。谢谢!!

这是我的代码:

Function DailyRange(YahooTicker As String, Optional dtDate As Variant)
' Date is optional - if omitted, use today. If value is not a date, throw error.
If IsMissing(dtDate) Then
dtDate = Date
Else
If Not (IsDate(dtDate)) Then
DailyRange = CVErr(xlErrNum)
End If
End If

Dim dtPrevDate As Date
Dim strURL As String, strCSV As String, strRows() As String, strColumns() As String
Dim DailyRows As Variant
Dim dbDate As String
Dim dbHigh As Double, dbLow As Double, dbClose As Double, dbVolume As Double

dtPrevDate = dtDate - 7

' Compile the request URL with start date and end date
strURL = "http://ichart.finance.yahoo.com/table.csv?s=" & YahooTicker & _
"&a=" & Month(dtPrevDate) - 1 & _
"&b=" & Day(dtPrevDate) & _
"&c=" & Year(dtPrevDate) & _
"&d=" & Month(dtDate) - 1 & _
"&e=" & Day(dtDate) & _
"&f=" & Year(dtDate) & _
"&g=d&ignore=.csv"

' Debug.Print strURL

Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", strURL, False
http.Send
strCSV = http.responseText

' Debug.Print strCSV

' THIS IS WHERE I RUN INTO THE PROBLEM    
' I want the most recent information which is in row 2, just below the table headings.
' I want date, price open, high, low, close, and volume which positions are shown below
strRows() = Split(strCSV, Chr(10)) ' split the CSV into rows
strColumns = Split(strRows(1), ",") ' split the relevant row into columns. 1 means 2nd row, starting at index 0
DailyRows = Join(strColumns, ",")
dbDate = strColumns(0) ' means 1st position, date
dbHigh = strColumns(2) ' means 3rd position, price high
dbLow = strColumns(3) ' means 4th position, price low
dbClose = strColumns(4) ' 4 means: 5th position, starting at index 0
dbVolume = strColumns(5) ' means 6th position, volume

' Now, how do I display the information I want in their own cells?
'DailyRange = dbDate & dbHigh & dbLow & dbClose & dbVolume
'DailyRange = strColumns
'DailyRange = strCSV

 DailyRange = DailyRows


Set http = Nothing

End Function
4

1 回答 1

0

如果您尝试打开 CSV,为什么不使用 Workbooks.Open() 方法打开文件,然后以这种方式操作数据?

于 2013-09-08T09:18:52.927 回答