VBA to copy and insert below when value is found

bettlejus

New Member
Joined
Apr 4, 2017
Messages
32
Dear all,

I need a VBA that finds a value found multiple times in a row and when it finds the value will copy the row where the value is and insert it below.

So far I have:

Sub copy_insert()
Dim c As Range
For Each c In Range("A1:A30")
If c.Value = "aaa" Then
c.EntireRow.Copy
c.Offset(1, 0).EntireRow.Insert
End If
Next c
End Sub

But this will always fail, if I comment the Insert or the copy line will work, but both together, no.

Please help me with a fix.

Thank you!
 

Excel Facts

Best way to learn Power Query?
Read M is for (Data) Monkey book by Ken Puls and Miguel Escobar. It is the complete guide to Power Query.
The problem you have is that the range is extending each time. Consider you have "aaa" in A1. Row 1 will be copied and inserted on row 2. The original range is now A1:A31 and the next cell considered will be A2 which now contains "aaa" so another line will be inserted. It's going to loop forever and since you don't have a "DoEvents" in there it's going to go into "Not Responding" mode. This might suit you better:

Code:
Sub copy_insert()

Dim thisRow As Long

For thisRow = 30 To 1 Step -1
    If Cells(thisRow, 1).Value = "aaa" Then
        Rows(thisRow).Copy
        Rows(thisRow + 1).Insert
        DoEvents
    End If
Next thisRow

Application.CutCopyMode = False

End Sub

WBD
 
Upvote 0

Forum statistics

Threads
1,214,897
Messages
6,122,151
Members
449,068
Latest member
shiz11713

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top