Search code examples
excelvbarowscopy-paste

copy specific rows to another sheet just if row contains a value


I want to copy a specific columns based on column A value.

Precisely, I want to copy columns A, C and D of sheet A to B, C and D of sheet B. But just the party where column A of sheet A contains AAAAA.

This example is just to simplify, in reality I have hundreds of rows so I need a necessary a loop and in sheet B I want to paste under the header:

How my Excel sheet looks:
[How my excel sheet looks][1

Sub COOPPYY()
    Dim N As Long, i As Long, j As Long, s As String
    Dim src As Worksheet
    Dim trg As Worksheet
    Dim LastRow As Long
    Dim c As Range

    N = Cells(Rows.Count, "B").End(xlUp).Row

    ' Change worksheet designations as needed
    Set src = ThisWorkbook.Worksheets("A")
    Set trg = ThisWorkbook.Worksheets("B")

    'For i = 1 To N
    'j = 1

    src.Range("A:A").Copy Destination:=trg.Range("B:B")
    src.Range("C:C").Copy Destination:=trg.Range("D:D")

    src.Range("D:D").Copy Destination:=trg.Range("C:C")
End Sub

How the second sheet looks where I want to copy:
how the second sheet looks where i want to copy


Solution

  • Something like this:

    Sub CopyIt()
    
        Dim N As Long, i As Long, j As Long, s As String
        Dim src As Worksheet
        Dim trg As Worksheet
    
        Set src = ThisWorkbook.Worksheets("A")
        Set trg = ThisWorkbook.Worksheets("B")
    
        N = src.Cells(src.Rows.Count, "B").End(xlUp).Row
        j = trg.cells(rows.count, "B").End(xlUp).Row + 1
    
        For i = 1 To N
            With src.Rows(i)             
                If .cells(1).Value = "AAAAA" Then
                    .cells(1).Copy trg.cells(j, "B")
                    .cells(3).Resize(1,2).copy trg.cells(j, "C")
                    j = j + 1 
                End If
             End With 
         Next i
    End Sub