Visual Basic循环

时间:2013-09-04 15:43:43

标签: excel excel-vba vba

我希望循环查询其下方单元格中的自动收报机并循环,直到它为列中的所有代码提取了该数据。

要点:

我正在尝试从A列中的股票代码中提取数据 这是我正在使用的代码。

Sub URL_Static_Query()


''Pull Data from Profile

With Sheet2.QueryTables.Add(Connection:= _
      "URL;http://finance.yahoo.com/q/pm?s=" & Sheet1.Range("A2").Value & "+Performance", _
         Destination:=Sheet2.Range("A1"))
 .BackgroundQuery = True
 .TablesOnlyFromHTML = True
 .Refresh BackgroundQuery:=False
 .SaveData = True

 End With

''Pull Data from Performance
 With Sheet3.QueryTables.Add(Connection:= _
      "URL;http://finance.yahoo.com/q/pr?s=" & Sheet1.Range("A2").Value & "+Profile", _
         Destination:=Sheet3.Range("A1"))

.BackgroundQuery = True
.TablesOnlyFromHTML = True
.Refresh BackgroundQuery:=False
.SaveData = True
End With

'Grab and Paste 3-month
Sheets("Sheet2").Select
Range("A1").Select

Cells.Find(What:="3-month", After:=ActiveCell, LookIn:=xlValues, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate

ActiveCell.Offset(0, 1).Select
Selection.Copy

Sheets("Sheet1").Select
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
ActiveSheet.Paste

'Grab and Paste 1-Year
Sheets("Sheet2").Select
Range("A1").Select

Cells.Find(What:="1-Year", After:=ActiveCell, LookIn:=xlValues, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate

ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

Sheets("Sheet1").Select
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 2).Select

Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=True

 Sheets("Sheet3").Select
 Range("A1").Select

 Cells.Find(What:="Prospectus Net Expense Ratio:", After:=ActiveCell, LookIn:=xlValues, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate

ActiveCell.Offset(0, 1).Select
Selection.Copy
Sheets("Sheet1").Select
Range("A1").Select
Selection.End(xlDown).Select
Selection.End(xlToRight).Select
ActiveCell.Offset(0, 1).Select
ActiveSheet.Paste

Sheet2.Cells.Clear
Sheet3.Cells.Clear

End Sub

1 个答案:

答案 0 :(得分:1)

您可以将此代码包装在一个循环中,该循环逐个按下列中的每个单元格。

例如,如果您使用的是A列,

Dim row_counter As Long, last_row As Long
row_counter = 1
'last_row = whatever your last row is

Do While row_counter < last_row
  '... put looping code here
  row_counter = row_counter + 1
Loop