Vba 使用for循环递增遍历图纸

Vba 使用for循环递增遍历图纸,vba,excel,for-loop,Vba,Excel,For Loop,我是VBA新手,代码有点问题。我有一张名为2001、2002、2003。。。2010我想依次挑选这些工作表,并对每个工作表执行一些简单的操作。我曾尝试使用for循环,从2000年增加到2010年,但它被卡住了。我认为问题在于我不知道如何指定它应该使用for循环选择的图纸名称 Sub Compile_data_from_worksheets() Dim i As Integer ' declare i as integer, this will count the number of Man

我是VBA新手,代码有点问题。我有一张名为2001、2002、2003。。。2010我想依次挑选这些工作表,并对每个工作表执行一些简单的操作。我曾尝试使用for循环,从2000年增加到2010年,但它被卡住了。我认为问题在于我不知道如何指定它应该使用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
}

问题是,如果在
工作表()
中放置了一个整数,则它假定您正在查找索引,就像在第2000张工作表中而不是在第2000张工作表中一样

换成

Sheets(cstr(i)).Select
也就是说,您确实应该处理代码并删除
。通过直接引用单元格选择
。一个好的资源是。它将大大加快速度,并有助于确保更少的错误

所以你的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