VBA复制和粘贴dynamic范围

我是新的VBA,我卡住了某个地方。 我必须复制列A的最后一行直到列H,并粘贴它,直到列I的最后一行。列的最后一行将总是改变。

例如; 我的数据是在A2:H2和I5是最后一个数据单元格。
我的代码应该是复制A2:H2并粘贴它A3:H5。 第二次运行macros(在向各列添加新数据之后),应该复制A6:H6并粘贴到第一列的最后一行。

我写了两个不符合我需要的代码。

第一个代码是

Sub OrderList1() Range("a65536").End(xlUp).Resize(1, 8).Copy _ (Cells(Cells(Rows.Count, 9).End(xlUp).Row, 1)) End Sub 

这段代码跳过A3:H4,只粘贴到A5:H5

第二个代码是 ;

  Sub OrderList2() Range("A2:H2").Copy Range(Cells(2, 8), _ Cells(Cells(Rows.Count, 9).End(xlUp).Row, 1)) End Sub 

它复制A2:H3并粘贴A5:H5,但是当我添加新的数据时,它不会从A5:H5开始粘贴。 它从A2:H2开始,并覆盖到旧的数据。 我可以看到我必须改变,范围应该像第一个代码中的dynamic范围,但我无法设法编写代码。

我真的很感激一点帮助。

你可能想用这个作为起点:

 Dim columnI As Range Set columnI = Range("I:I") Dim columnA As Range Set columnA = Range("A:A") ' find first row for which cell in column A is empty Dim c As Range Dim i As Long i = 1 For Each c In columnA.Cells If c.Value2 = "" Then Exit For i = i + 1 Next c ' ok, we've found it, now we can refer to range from columns A to H of the previous row ' to a variable (in the previous row, column A has not been empty, so it's the row we want ' to copy) Dim lastNonEmptyRow As Range Set lastNonEmptyRow = Range(Cells(i - 1, 1), Cells(i - 1, 8)) ' and now copy this range to all further lines, as long as columnI is not empty Do While columnI(i) <> "" lastNonEmptyRow.Copy Range(Cells(i, 1), Cells(i, 8)) i = i + 1 Loop 

尝试这一个东西,允许未来的function,或者至less它做了我…问你是否需要帮助理解它:)

 Option Explicit Sub lastrow() Dim wsS1 As Worksheet 'Sheet1 Dim lastrow As Long Dim lastrow2 As Long Set wsS1 = Sheets("Sheet1") With wsS1 'Last row in A lastrow = Range("A" & Rows.Count).End(xlUp).Row 'Last Row in I lastrow2 = Range("I" & Rows.Count).End(xlUp).Row 'Cut in A:H and paste into last row on I wsS1.Range("A2:H" & lastrow).Cut wsS1.Range("I" & lastrow2) End With End Sub