Search code examples
excelvba

I need a VBA script to copy and paste rows in excel with a certain step


I need an Excel macro that will copy every sixth row of a particular worksheet, starting from the seventh row, and paste the values ​​of these rows (without shifting or deleting the copied rows containing the formulas) into every sixth row of the same worksheet, starting from the fifth row (Accordingly, copy the formula values ​​of the seventh line and paste into the fifth, copy 13 and paste into 11, and so on until the last significant line). I don’t understand programming at all, and neither neural networks nor my attempts gave the desired result. I ask you for help, friends.

Sub Copy_And_Insert_Rows()
    Dim i As Integer
    Dim lastRow As Integer

    lastRow = Cells(Rows.Count, 1).End(xlUp).Row

    For i = 6 To lastRow Step 6
        Rows(i).Copy
        Rows(i - 2).Insert Shift:=xlDown
    Next i

    Application.CutCopyMode = False
End Sub

The neural network produced this result, but it does not do what I need, shifting the rows down.

At the request of the commentator, I am clarifying my requirements for the macro. I made the following code for three lines:

Sub Copy_And_Insert_Rows()
Range("d7:crg7").Copy
Range("d5:crg5").PasteSpecial xlPasteValues
Range("d13:crg13").Copy
Range("d11:crg11").PasteSpecial xlPasteValues
Range("d19:crg19").Copy
Range("d17:crg17").PasteSpecial xlPasteValues
End Sub

Essentially I need the same thing, but for several thousand lines, which requires more advanced code.


Solution

  • Try this code:

    Sub Copy_Rows()
        Dim i As Long
        Dim lastRow As Long
    
        lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    
        For i = 7 To lastRow Step 6
            Rows(i).Columns("B:CRG").Copy
            Rows(i - 2).Columns("B:CRG").PasteSpecial xlPasteValues
        Next i
    
        Application.CutCopyMode = False
    End Sub
    

    You may restrict copy/paste to columns you actually need.