0

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

此外,如果我可以为使用相应 NYSE 名称查询的每个 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
4

1 回答 1

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
于 2015-04-06T18:14:36.087 回答