使用 For 循环遍历字符串 +

Using For loop through string +

首先,我想说这是我第一次尝试构建 vba 代码。我正在尝试使用网络查询 .Add(Connection,Destination,sql) 从网络中提取数据。我想要我的代码做的是循环遍历字符串 'str',其中包含要插入到我的 url 中的股票代码,使用 for 循环并将 table 数据粘贴到活动 sheet.

此外,如果我可以为每个使用相应 NYSE 名称查询的 url 创建一个新的 sheet,那就更好了。

目前我的代码没有 运行 因为它没有提取数据。我认为错误在于我如何使用循环索引 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

看看这对你有用:

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