1

I using the below macro and it inserts the row below the cell with "Card Number"

I cannot get it to go above the row no matter what I do. Probably quite basic for some but have recently only found how useful macros are

Sub Insert()
Dim c As Range
For Each c In Range("A1:A5000")
If c.Value Like "*Card Number:*" Then
c.Offset(1, 0).EntireRow.Insert
End If
Next c
End Sub
R3uK
  • 14,417
  • 7
  • 43
  • 77
Miss G
  • 13
  • 1
  • 3

3 Answers3

1

As you probably tried you cannot just do c.EntireRow.Insert since it will insert a line above and it will keep in the For Each loop infinitely. The solution is to loop through the range in reverse, like done in this answer:

Sub InsertRev()
    Dim c As Range
    Set rng = ActiveSheet.Range("A1:A5000")
    For dblCounter = rng.Cells.Count To 1 Step -1
        Set c = rng(dblCounter)
        If c.Value Like "*Card Number:*" Then
           c.EntireRow.Insert
        End If
    Next dblCounter
End Sub
agold
  • 6,140
  • 9
  • 38
  • 54
0

This is how I would solve this problem but I'm not that advanced in macros and I'm sure there is a better way.

Sub Insert()
For i = 1 To 5000
   If Cells(i, "A") Like "*Card Number:*" Then ' loop trough 5000 cells in column A
       Rows(i + 1).Insert 'insert bottom row first so it doesn't mess with row numbers
       Rows(i - 1).Insert 'then you can insert upper row
       i = i + 1 'jump over the next row as it now contains the card number for sure
   End If
Next i
End Sub
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Uroš Grum
  • 138
  • 2
  • 14
  • 1
    It would be easier to use `Step -1` to go from bottom to top, to avoid adding multiples rows! ;) – R3uK Nov 26 '15 at 10:26
0

Don't use the Offset in that case, the Insert command always insert rows above the selection.

Further more, if you use for each, you don't have control on the direction in which your loop will be, so it is better to use for i = with step -1 to go from bottom to top.

Why? Because if you insert a new row from row i, the row i will become the row i+1 and you will test it on the next loop and keep adding rows!

Sub Insert_Rows()
Dim i As Long

For i = 5000 To 1 Step -1
    If Cells(i, "A").Value Like "*Card Number:*" Then
        Cells(i, "A").EntireRow.Insert
    End If
Next i
End Sub
R3uK
  • 14,417
  • 7
  • 43
  • 77