Excel VBA复制和粘贴环路限制范围内的循环

Newbee在这里同时提供这个网站和Excel VBA。 我在下面的post中使用了RichA的代码,并且能够使它适用于从另一个工作表中填充/复制工作表(Sheet2)上的数据的目的。

代码链接到原始发布Excel VBA复制并粘贴循环内循环

我有一个关于如何将范围限制在这个代码中的“命名范围”(C13:Z111)而不是“整列”(“C”)的问题。 我似乎无法得到它限制复制行,从数据的最后一行开始,倒数第一行。

我有一些行(C1:C12)的标题在顶部和数据从第13行开始。所以当从一个工作表复制到另一个工作表,顶部的行也复制。 我想结束在第13行的数据复制。

感谢您的帮助。

这里是目前的例外,我不能限制范围。

Sub Generate_Invoice() Dim i As Long Dim ii As Long Dim i3 As Long Dim LastRow As Long Dim wb As Workbook Dim sht1 As Worksheet Dim sht2 As Worksheet Set wb = ThisWorkbook Set sht1 = wb.Sheets("INCENTIVE") Set sht2 = wb.Sheets("Sheet2") Sheets("Sheet2").Select Range("B11:Z200").ClearContents 'Find the last row (in column C) with data. LastRow = sht1.Range("C13:C111").Find("*", searchdirection:=xlPrevious).Row ii = 2 'This is the beginning of the loop >>>This Works BUT BUT BUT goes all the way to the top - REQUESTING HELP WITH CODE ENDS AT ROW 13 AND DOES NOT GO PAST<<< For i = 3 To LastRow 'First activity sht2.Range("B" & ii) = sht1.Range("C" & i).Value sht2.Range("C" & ii) = sht1.Range("G" & i).Value sht2.Range("D" & ii) = sht1.Range("H" & i).Value sht2.Range("E" & ii) = sht1.Range("P" & i).Value sht2.Range("F" & ii) = sht1.Range("R" & i).Value sht2.Range("G" & ii) = sht1.Range("AD" & i).Value ii = ii + 1 Next i 'Return to "Sheet2" Sheets("Sheet2").Select 'Add SUM at bottom of last record in Range"D" Dim ws As Worksheet For Each ws In Worksheets With ws.Range("F" & Rows.Count).End(xlUp).Offset(2) .FormulaR1C1 = "=SUM(R11C6:R[-1]C6)" .Offset(, -1).Value = "Total:" End With Next ws End Sub 

你正在寻找最后一排,但只在人口稠密的地区。 我build议通过在工作表底部开始并find列C中最后一个填充的单元格来改变最后一行的确定方法。这就像在C1048576中敲击Ctrl +

 'Find the last row (in column C) with data. LastRow = sht1.Cells(Rows.Count, "C").End(xlUp).Row 'not sure whether you want to reverse this as well ii = 2 'This is the beginning of the loop >>>This Works BUT BUT BUT goes all the way to the top - REQUESTING HELP WITH CODE ENDS AT ROW 13 AND DOES NOT GO PAST<<< For i = LastRow To 13 Step -1 'work from the bottom to the top. 'First activity sht2.Range("B" & ii) = sht1.Range("C" & i).Value sht2.Range("C" & ii) = sht1.Range("G" & i).Value sht2.Range("D" & ii) = sht1.Range("H" & i).Value sht2.Range("E" & ii) = sht1.Range("P" & i).Value sht2.Range("F" & ii) = sht1.Range("R" & i).Value sht2.Range("G" & ii) = sht1.Range("AD" & i).Value 'not sure whether you want to reverse this as well ii = ii + 1 Next i 

你只需要根据你想要的标准退出for循环。 例如:

 If ii = 13 Then Exit For