使用For循环string+

首先,我想说这是我第一次尝试构buildvba代码。 我正试图从Web提取数据使用Web查询。添加(连接,目标,SQL)。 我想要的代码是通过包含股票代码的string“str”循环,使用for循环将其插入到我的url中,并粘贴活动工作表中的表格数据。

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

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

感谢您的回复,build议和build议。

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