简体   繁体   中英

VBA copy & paste with dynamic range

I'm new with VBA and I'm stuck somewhere. I have to copy last row of column A till column H and paste it untill the last row of column I. Last rows of columnns will be always change.

eg; my data is in A2:H2 and I5 is the last cell with data.
My code should be copy A2:H2 and paste it A3:H5. And second time I run the macro (after I add new data to respective columns) it should be copy A6:H6 and paste it untill the last row of column I.

I wrote two codes which were not fulfill my needs.

first code is ;

  Sub OrderList1()

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

  End Sub

this code skips A3:H4 and only pastes to A5:H5

second code is ;

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

 End Sub

it copies A2:H3 and paste it A5:H5 but when I add new data it doesn't start to paste from A5:H5. It start from A2:H2 and overwrite to old data. I can see what I have to change,range should be dynamic range like in the first code,but I can't manage to write the code.

I'll really appreciate little help.

You might want to use this as a starting point:

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

Try this one for something that allows future functionality, or at least it did for me...Ask if you need help understanding it :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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