我是VBA的新手,无法为我的生活解决这个问题。如果我没有使用正确的词语来描述我的问题,我道歉:
我在VBA中有一个函数可以打开一个下载csv文件的URL。我将变量分配给声明为“As String”的下载。然后,我将其拆分为行并将相关行(我需要第二行中的信息)拆分为列。我现在可以使用该函数在第二行的七列中的任何一列中显示任何信息,但一次只能显示一列。我还可以使用Join()方法在一个单元格中显示整个第二行,子串用逗号分隔。
目标:我希望能够自定义要显示的第二行中的哪些信息(子串),并且我希望它们显示在它们自己的相邻单元格中(按列相邻)。这可以通过使用数据功能区上的“文本到列”功能来实现,但我希望它在可视化基本代码本身中进行转换。谢谢!!
这是我的代码:
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
答案 0 :(得分:0)
如果您尝试打开CSV,为什么不使用Workbooks.Open()方法打开文件,然后以这种方式操作数据?