简体   繁体   中英

How to copy an entire row to another sheet if a cell = true

I have 2 sheets, 'Initial' & 'Report1'. I'm trying to copy specific rows from 'Inital' to 'Report1' when the cell in column 'H' is = "On going". I have the function as a button in excel but cant workout how to copy and paste the line and move onto the next cell.
Also, Column D is formula and needs to be pasted special to copy over.

I have attached the current code I have tried but it errors. Any help would be greatly appreciated.

Sub GenRep1_Click()

    Dim Inti As Worksheet
    Dim rep1 As Worksheet

    Set Inti = ThisWorkbook.Worksheets("Inital")
    Set rep1 = ThisWorkbook.Worksheets("Report1")

    Dim rngA As Range
    Dim cell As Range

    Set rngA = Sheets("Inti").Range("H5:H9999")
    For Each cell In rngA
        If cell.Value = "On going" Then
            cell.EntireRow.Copy
            Sheets("Inti").Range("").End(xlDown).Select
            ActiveSheet.Paste
        End If
    Next cell

End Sub

I expect the all rows in column 'H' that = "On Going" to be copied to "Report1".

I think this does what you want. You might want to improve the range you're looping through in case you only have, eg 100 cells of data.

A quicker approach than looping would be AutoFilter.

Sub GenRep1_Click()

Dim Inti As Worksheet
Dim rep1 As Worksheet

Set Inti = ThisWorkbook.Worksheets("Inital") 'check name - typo?
Set rep1 = ThisWorkbook.Worksheets("Report1")

Dim rngA As Range
Dim cell As Range

Set rngA = Inti.Range("H5:H9999") 'already defined worksheet so just use variable
'Set rngA = Inti.Range("H5",inti.range("H" & rows.count).end(xlup))  'would be more efficient

For Each cell In rngA
    If cell.Value = "On going" Then
        cell.EntireRow.Copy
        repl.Range("A" & Rows.Count).End(xlUp)(2).PasteSpecial xlValues 'copy to the other sheet
    End If
Next cell

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