Home » excel » excel – macro to duplicate rows previously worked, now not working but no error message?

excel – macro to duplicate rows previously worked, now not working but no error message?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am using the following macro to duplicate information from one row into a blank one (that I’ve already generated) below. This macro worked ~ a month ago, but when I run it now, nothing happens, despite there being no error message.

Sub FillEveryOther()

Dim lastRow As Long
Dim i As Long

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

For i = 2 To i = lastRow Step 2
        Rows(i).EntireRow.Select
        Selection.Copy
        Rows(i + 1).EntireRow.Select
        ActiveSheet.Paste
     If i = lastRow + 1 Then Stop
Next i

End Sub
How to&Answers:

You’re never entering the loop due to the fact that

For i = 2 to i = lastRow Step 2

is functionally the same as

For i = 2 to False Step 2

Since False evaluates to 0, it’s really saying

For i = 2 to 0 Step 2

and so it never enters the loop.

Just change it to

For i = 2 To lastRow Step 2

EDIT:

Just for clarity, whether the statement evaluates True or False, it still won’t enter the loop as False evaluates 0 and True evaluates -1.

Answer:

Fill Every Other Row with Previous

The Code

Sub FillEveryOther()

    Const cCol As Variant = 12    ' Last-Row-Column Letter/Number
    Const cFirstRow As Long = 2   ' First Row Number

    Dim lastRow As Long   ' Last Row Number
    Dim i As Long         ' Cell (Row) Counter

    ' Calculate Last Row Number in Last-Row-Column.
    lastRow = Cells(Rows.Count, cCol).End(xlUp).Row

    ' Loop through every other cell (row) of Last-Row-Column.
    For i = cFirstRow To lastRow Step 2
        ' Copy current row to the row below.
        Rows(i).Copy Rows(i + 1)
    Next

End Sub

An Improvement?

The following code allows the rows not to strictly be even (2,4,6…) and there can be more than one empty row below. But there always has to be data in the cells of cCol or a formula in them (IsEmpty).

Sub CopyNotEmpty()

    Const cCol As Variant = 12    ' Last-Row-Column Letter/Number
    Const cFirstRow As Long = 2   ' First Row Number

    Dim lastRow As Long   ' Last Row Number
    Dim i As Long         ' Cell (Row) Counter

    ' Calculate Last Row Number in Last-Row-Column.
    lastRow = Cells(Rows.Count, cCol).End(xlUp).Row

    ' Loop through cells (rows) of Last-Row-Column.
    For i = cFirstRow To lastRow
        ' Check if there is data in current cell.
        If Not IsEmpty(Cells(i, cCol)) Then
            ' Copy current row a row below.
            Rows(i).Copy Rows(i + 1)
            ' Increase Cell (Row) Counter, because we don't want to copy
            ' the already copied row.
            i = i + 1
        End If
    Next

End Sub