使用For循环通过字符串+

时间:2015-04-06 18:04:14

标签: excel vba financial excel-web-query

首先,我想说这是我第一次尝试构建vba代码。我正在尝试使用Web查询从Web中提取数据.Add(Connection,Destination,sql)。我希望我的代码要做的是遍历字符串' str'包含要使用for循环插入到我的URL中并使用活动工作表中的表数据粘贴的股票行情。

此外,如果我可以为每个使用相应纽约证券交易所名称查询的网址创建新工作表,那将是额外的工作。

目前我的代码没有运行,因为它没有提取数据。我认为错误在于我如何使用循环索引NYSE(i)指定url。

感谢您的任何回复,建议和建议。

Sub URL_Get_Query()


Dim NYSE(1 To 22) As String
NYSE(1) = "APC"
NYSE(2) = "APA"
NYSE(3) = "COG"
NYSE(4) = "CHK"
NYSE(5) = "XEC"
NYSE(6) = "CRK"
NYSE(7) = "CLR"
NYSE(8) = "DNR"
NYSE(9) = "DVN"
NYSE(10) = "ECA"
NYSE(11) = "EOG"
NYSE(12) = "XCO"
NYSE(13) = "MHR"
NYSE(14) = "NFX"
NYSE(15) = "NBL"
NYSE(16) = "PXD"
NYSE(17) = "RRC"
NYSE(18) = "ROSE"
NYSE(19) = "SD"
NYSE(20) = "SWN"
NYSE(21) = "SFY"
NYSE(22) = "WLL"
For i = 1 To 22
  Debug.Print NYSE(i)
   With ActiveSheet.QueryTables.Add(Connection:= _
      "URL;http://finance.yahoo.com/q/ks?s=NYSE(i)+Key+Statistics", _
         Destination:=Range("a1"))

      .BackgroundQuery = True
      .TablesOnlyFromHTML = True
      .Refresh BackgroundQuery:=False
      .SaveData = True
   End With
Next i
End Sub

1 个答案:

答案 0 :(得分:1)

了解这对您有何帮助:

Dim NYSE_List As String, i As Long
Dim NYSE
NYSE_List = "APC,APA,COG,CHK,XEC,CRK,CLR,DNR,DVN,ECA,EOG,XCO,MHR,NFX,NBL,PXD,RRC,ROSE,SD,SWN,SFY,WLL"
' this is easier to maintain. Split the list at the commas.
' No need to count absolute numbers, either.
NYSE = Split(NYSE_List, ",")

For i = 0 To UBound(NYSE)
  Dim ws As Worksheet
  ' Insert a new worksheet after the last one (each time)
  Set ws = Worksheets.Add(after:=Worksheets(Worksheets.Count))
  ws.Name = NYSE(i)
  Debug.Print NYSE(i)

 ' assemble the variable into the string:
  With ws.QueryTables.Add(Connection:= _
      "URL;http://finance.yahoo.com/q/ks?s=" & NYSE(i) & "+Key+Statistics", _
         Destination:=ws.Range("a1"))
       ' note that the range must address the proper worksheet object

      .BackgroundQuery = True
      .TablesOnlyFromHTML = True
      .Refresh BackgroundQuery:=False
      .SaveData = True
   End With
Next i