循环中的Excel vba复制和粘贴循环 - 限制范围

时间:2015-12-06 15:41:35

标签: excel vba excel-vba

Newbee来到这个网站和Excel VBA。我在下面的文章中使用了RichA的代码,并且能够使其在我从另一张表格中填充/复制工作表(Sheet2)中的数据方面运行良好。

代码链接到原始帖子 Excel VBA Copy and Paste Loop within Loop

我有一个关于如何将范围限制为“命名范围”(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

2 个答案:

答案 0 :(得分:2)

您正在寻找最后一行,但只查看人口稠密区域。我建议更改最后一行的方法,从工作表底部开始,找到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

答案 1 :(得分:0)

您只需根据所需条件退出for循环即可。例如:

If ii = 13 Then Exit For