请帮忙,我正在使用下面的代码。我只需要数据进入第 N 列,当使用 for 循环时,它会遍历所有列。我该如何解决这个问题?
Dim W As Worksheet: Set W = ActiveSheet
Last = W.Range("A1500").End(xlUp).Row
If Last = 7 Then Exit Sub
Dim Symbols As String
Dim i As Integer
Dim j As Integer
' Code below Loops on the stock tickers and concatenate them
For i = 8 To Last Step 200
Symbols = "" 'value to reset the string during loop
For j = i To i + 199
Symbols = Symbols & W.Cells(j, 1) & "+"
Next j
Symbols = Left(Symbols, Len(Symbols) - 1)
'Debug.Print Symbols ' delete this later
Dim URL As String: URL = "http://finance.yahoo.com/d/quotes.csv?s=" & Symbols & "&f=snl1p2kjr5rp6s7m3m8"
With ActiveSheet.QueryTables.Add(Connection:="URL;" & URL, Destination:=W.Range("$N$" & i))
.BackgroundQuery = True
.TablesOnlyFromHTML = True
.Refresh BackgroundQuery:=False
.FillAdjacentFormulas = False
.SaveData = True
End With
Next i
答案1
该问题似乎是由于添加新内容QueryTable
会将先前添加的内容QueryTable
向右推一列而引起的。
可以通过在语句后立即添加以下代码来撤消此操作End With
。对于第一个语句之后的每个新QueryTable
语句,这将删除先前添加的单元格左侧的单列单元格QueryTable
,从而重新水平对齐它们。
If i <> 8 Then
Range("N8", W.Range("$N$" & i).Offset(-1)).Delete (xlShiftToLeft)
End If