VBA副本&粘贴动态范围

时间:2012-08-27 08:34:14

标签: excel vba dynamic excel-vba range

我是VBA的新手,我被困在某个地方。我必须将A列的最后一行复制到H列,然后将其粘贴到第I列的最后一行。最后一列的列将始终更改。

e.g;我的数据在A2:H2和I5是最后一个有数据的单元格 我的代码应该是复制A2:H2并将其粘贴到A3:H5。第二次运行宏(在我向各列添加新数据之后)应该复制A6:H6并将其粘贴到第I列的最后一行。

我写了两个不能满足我需要的代码。

第一个代码是;

  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开始并覆盖旧数据。 我可以看到我要改变的东西,范围应该像第一个代码中的动态范围,但我无法设法编写代码。

我真的很感激你的帮助。

2 个答案:

答案 0 :(得分:2)

您可能希望将此作为起点:

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

答案 1 :(得分:1)

尝试使用这个可以实现未来功能的东西,或者至少它对我有用...询问您是否需要帮助理解它:)

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