繁体   English   中英

Excel VBA在循环内复制和粘贴循环-限制范围

[英]Excel vba copy and paste loop within loop - limit range

Newbee在此访问此站点和Excel VBA。 我在下面的文章中使用了RichA的代码,并能够使其正常工作,以实现我从另一个工作表填充/复制工作表(Sheet2)中的数据的目的。

代码链接到原始POST Excel VBA在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

您在寻找最后一行,但只在填充区域内寻找。 我建议通过从工作表的底部开始并在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM