2015-10-20 176 views
0

我是VBA的新手,並且遇到了一些代碼問題。我有名爲2001,2002,2003 ... 2010的工作表。我想依次選擇這些表中的每一個,並在每個工作表上執行一些簡單的操作。我試圖使用for循環,從2000年到2010年增加,但它陷入了困境。我認爲問題是我不知道如何指定它應該使用for循環選擇的表名。使用for循環遞增遍歷表

Sub Compile_data_from_worksheets() 

Dim i As Integer ' declare i as integer, this will count the number of Manufacturers 
Dim y As Long  ' declare y as long, this will capture the number of rows in a worksheet 
Dim x As String ' declare x as string, this will capture the name of each Manufacturer 

Application.StatusBar = "running macro" ' places message on the statusbar while macro runs 

ThisWorkbook.Activate 

Application.ScreenUpdating = False 'stop the screen updating as the macro runs 
Application.CutCopyMode = False  'clears the clipboard 


For i = 2000 To 2002    ' for each of the years in turn 

Sheets(i).Select   ' activate worksheet 2000 
Range("A17").Select 
Range(Selection, Selection.End(xlDown)).Select 
Range(Selection, Selection.End(xlToRight)).Select 
Selection.Copy 

Worksheets("Combined_data").Activate 

y = ActiveSheet.UsedRange.Rows.Count  'count how many rows of worksheet "AllData_Raw" have been used so far. 

Cells(y + 1, 1).Select   'use the Cells command to select data and then paste selection 

ActiveSheet.Paste 

Next i       ' next year... 

End Sub 
} 

回答

0

的問題是,如果一個整數放在裏面Sheets(),它假設你正在尋找的指標,如第2000片不表2000

將其更改爲

Sheets(cstr(i)).Select 

這就是說,你真的應該通過你的代碼,並通過直接引用單元格刪除.select。一個好的資源是here。它將大大加快速度並幫助確保更少的錯誤。

所以,你的for循環是這樣

For i = 2000 To 2002    ' for each of the years in turn 
    With Sheets(CStr(i)) 
     .Range(.Range("A17"), .Range("A17").End(xlDown).End(xlToLeft)).Copy 
    End With 
    With Worksheets("Combined_data") 
     y = .UsedRange.Rows.Count  'count how many rows of worksheet "AllData_Raw" have been used so far. 
     .Cells(y + 1, 1).Paste 
    End With 
Next i