0

First, I want to say that this is my first attempt at building vba code. I am trying to extract data from the web using a web query .Add(Connection,Destination,sql). What I want my code to do is to loop through the string 'str' containing stock tickers to be inserted into my url using a for loop and pasting the table data in the active sheet.

In addition, it would be an extra if I could create a new sheet for every url queried with the corresponding NYSE name.

Currently my code does not run because it is not extracting the data. I think the error is in how I am specifying the url using the loop index NYSE(i).

Thanks for any responses, advice, and suggestions.

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
drap
  • 3
  • 1
  • try : `With ActiveSheet.QueryTables.Add(Connection:= "URL;http://finance.yahoo.com/q/ks?s=" & NYSE(i) & "+Key+Statistics", Destination:=Range("a1"))` – scraaappy Apr 06 '15 at 18:09

1 Answers1

1

See how this works for you:

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
KekuSemau
  • 6,830
  • 4
  • 24
  • 34
  • This is what I was looking for. However, when I run it a message pops up "Invalid outside procedure". Would it have to do with running a Mac? – drap Apr 08 '15 at 21:16
  • You still have to put the code inside a sub, just like in your own example. – KekuSemau Apr 09 '15 at 17:39