Search code examples
excelloopscopy-pastevba

Copy-paste specific columns from rows if an If condition is satisfied


I am trying to build a macro to copy paste specific columns from rows, when an If condition is satisfied. The part of the If condition is tested and working, as I have used it in another macro. The problem in my case is that I dont know how to select specific columns of a row inside a loop. I only know how to select the entire row (in this case it would have been rows(i).EntireRow.Copy if I am not mistaken). I am providing my code below. The part that needs editing is the

.Rows(i).Columns(1, 4, 6, 8).Copy
Sheets("WFRandVFR_REPORT").range("W2").Paste

The entire code is this one

(UPDATED VERSION)

I am providing the screenshots too

enter image description here enter image description here

Dim lr As Long
Dim rng As range
Dim mDiff1 As Double
mDiff1 = 0.01
With Worksheets("WFRandVFR_REPORT")
    lr = range("L" & Rows.Count).End(xlUp).Row
    For i = 2 To lr
        If Cells(i, "U").Value - Cells(i, "V").Value > mDiff1 Then
            If rng Is Nothing Then
                Set rng = .range("L" & i & ":V" & i)
            Else
                Set rng = Union(rng, .range("L" & i & ":V" & i))
            End If
        End If
    Next i
    rng.Copy
    Sheets("WFRandVFR_REPORT").range("AI2").PasteSpecial
End With

Solution

  • To copy you may use

    Range("A" & i & ", D" & i & ", F" & i & ", H" & i & "").Copy  '(as mentioned in comment)
    

    or

    Union(.Range("A" & i), .Range("D" & i), .Range("F" & i), .Range("H" & i)).Copy
    

    Thus, try

    Union(.Range("A" & i), .Range("D" & i), .Range("F" & i), .Range("H" & i)).Copy
    Sheets("WFRandVFR_REPORT").range("W2").PasteSpecial xlPasteValues
    

    or just

    Union(.Range("A" & i), .Range("D" & i), .Range("F" & i), .Range("H" & i)).Copy
    Sheets("WFRandVFR_REPORT").range("W2").PasteSpecial
    

    or

    Union(.Range("A" & i), .Range("D" & i), .Range("F" & i), .Range("H" & i)).Copy Sheets("WFRandVFR_REPORT").range("W2")
    

    EDIT :

    Is there any specific reason why you are looping from bottom to up, if not change FOR loop as

    For i = 2 To lastrow
    

    Your code will be

    Dim mDiff As Integer
    Dim rng As Range
    mDiff = 0.03
    With Worksheets("WFRandVFR_REPORT")
        lastrow = Range("L" & Rows.Count).End(xlUp).Row
        For i = 2 To lastrow
            If Cells(i, "U").Value - Cells(i, "V").Value > mDiff Then
                If rng Is Nothing Then
                    Set rng = .Range("L" & i & ":V" & i)
                Else
                    Set rng = Union(rng, .Range("L" & i & ":V" & i))
                End If
            End If
        Next i
        rng.Copy
        Sheets("WFRandVFR_REPORT").Range("AI2").PasteSpecial
    End With