VBA copy & paste with dynamic range

旧巷老猫 提交于 2019-12-02 08:22:12

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!