简体   繁体   中英

How to cut/paste rows from one Excel sheet to 1st blank row of another sheet

I need any row in Sheet1 that has the word 'Done' in column E to be cut and pasted into the next empty row of Sheet2. My problem is that I don't know how to find the next empty row in Sheet2 and start pasting values to that next empty row.

It's a basic Workbook with two Sheets. Sheet1 has all employee tasks and Sheet2 only displays the tasks that are 'Done'. Anytime an employee finishes a task and types 'Done' in a cell within Column E of Sheet1, that entire row needs to be cut and pasted into the next empty row of Sheet2. I created an ActiveX Command button in Sheet1 with the following code. The code finds any cell in Sheet1 that says 'Done' and cuts/pastes it in Sheet2, but it always starts pasting from the beginning of Sheet2, and I need it to start pasting from the next empty row of Sheet2.

Private Sub CommandButton1_Click()
Dim c As Range
Dim j As Integer
Dim Source As Worksheet
Dim Target As Worksheet

' Change worksheet designations as needed
Set Source = ActiveWorkbook.Worksheets("Sheet1")
Set Target = ActiveWorkbook.Worksheets("Sheet2")

j = 1     ' Start copying to row 1 in target sheet
For Each c In Source.Range("E1:E1000")   ' Do 1000 rows
    If c = "Done" Then
       Source.Rows(c.Row).Cut Target.Rows(j)
       j = j + 1
    End If
Next c
End Sub

My problem is that it keeps overwriting anything that's already in Sheet2 because I don't know what to replace that 'j' variable code with. I need it to find the next empty row in Sheet2 and start pasting from there.

Give this a go:

Private Sub CommandButton1_Click()
Dim Source As Worksheet
Dim Target As Worksheet

Dim lRowSrc As Long, lRowDst As Long, lColSrc As Long, R As Long

' Change worksheet designations as needed
Set Source = ActiveWorkbook.Worksheets("Sheet1")
Set Target = ActiveWorkbook.Worksheets("Sheet2")

With Source
    lRowSrc = .Cells(.Rows.Count, 1).End(xlUp).row
    lColSrc = .Cells(1, .Columns.Count).End(xlToLeft).Column

    For R = lRowSrc To 1 Step -1
        If .Cells(R, 5) = "Done" Then
            lRowDst = Target.Cells(Target.Rows.Count, 1).End(xlUp).row

            Target.Range(Target.Cells(lRowDst + 1, 1), Target.Cells(lRowDst + 1, lColSrc)).Value = .Range(.Cells(R, 1), .Cells(R, lColSrc)).Value
            .Cells(R, 5).EntireRow.Delete   'get rid of the row
        End If
    Next R
End With

End Sub

Keep in mind that with a large data set, this aproach is not ideal, and using arrays is much much better. If however you only have a small number of rows (assume so...), it should be fine.

EDIT: used last row variable instead of the current row for copying values. Fixed.

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