2015-04-06 111 views
0

首先,我想說這是我第一次嘗試構建vba代碼。我正嘗試使用Web查詢來提取網絡中的數據.Add(Connection,Destination,sql)。我想要的代碼是通過包含股票代碼的字符串「str」循環,使用for循環並將表格數據粘貼到活動工作表中。使用For循環字符串+

此外,如果我可以爲每個使用相應的紐約證券交易所名稱查詢的網址創建一個新工作表,那將是額外的工作。

目前我的代碼不運行,因爲它不提取數據。我認爲錯誤在於我如何使用循環索引NYSE(i)指定網址。

感謝您的任何迴應,建議和建議。

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 
+0

嘗試:'隨着ActiveSheet.QueryTables.Add(連接:=「網址; HTTP://finance.yahoo.com/q/ks? s =「&NYSE(i)&」+ Key + Statistics「,Destination:= Range(」a1「))' – scraaappy

+0

This works。謝謝!! – drap

回答

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 
+0

這就是我一直在尋找的東西。但是,當我運行它時會彈出一條消息「外部程序無效」。是否需要運行Mac? – drap

+0

您仍然必須將代碼放入子文件中,就像在您自己的示例中一樣。 – KekuSemau