VBA复制和粘贴与动态范围(VBA copy & paste with dynamic range)

2019-06-27 09:44发布

我是新用VBA,我什么地方卡住了。 我要列A的最后一行复制至H列,并粘贴,直到列一columnns的最后一行将随时更改的最后一排。

例如; 我的数据在A2:H2和I5是与数据的最后一个单元格。
我的代码应该是复制A2:H2和粘贴A3:H5。 而我第二次运行宏(在我的新数据添加到相应的列)应该复制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和覆盖旧数据。 我可以看到我有什么改变,范围应该是动态的范围像在第一代码,但我不能设法写代码。

我会很感激一些帮助。

Answer 1:

你可能想以此为出发点:

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


Answer 2:

试试这个东西,可以让未来的功能,或者在它为我做的最...询问是否需要帮助理解吧:)

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


文章来源: VBA copy & paste with dynamic range