简体   繁体   中英

How do I loop through cells and create a new row if it contains a specific string in vba?

I want to loop through all the cells in column A with content and create a new row above a cell if it contains a specific string. Here is the code I have so far:

 Dim rng_cell As Range

    For Each rng_cell In Range(Range("A1"), Range("A1").End(xlDown))

        If rng_cell.Value = "string" Then
            rng_cell.EntireRow.Insert xlUp
        End If

    Next rng_cell

Any idea why this doesn't work and how to fix it?

Let's say your Excel sheet contained the following:

   A
1  hello
2  moon
3  rich
4  dells
5  cat

The reason your macro wasn't working as desired is because you were successfully creating a new line and then immediately the macro was dropping to the next line and finding the same match, and adding a new empty line, and going to the next line and finding the same match...and on and on.

If we wanted to enter a new line above the line with rich , a macro like this might work better:

Sub macro1()
    Range("A1").Select

    ' remember the last row that contains a value
    Dim LastRow As Integer
    Dim CurrentRow As Integer
    LastRow = Range("A1").End(xlDown).Row
    CurrentRow = 1

    ' keep on incrementing the current row until we are
    ' past the last row
    Do While CurrentRow <= LastRow

        ' if the desired string is found, insert a row above
        ' the current row
        ' That also means, our last row is going to be one more
        ' row down
        ' And that also means, we must double-increment our current
        ' row
        If Range("A" & CurrentRow).Value = "rich" Then
            Range("A" & CurrentRow).EntireRow.Insert xlUp
            LastRow = LastRow + 1
            CurrentRow = CurrentRow + 1
        End If

        ' put the pointer to the next row we want to evaluate
        CurrentRow = CurrentRow + 1

    Loop

End Sub

After running this, the output will look like this:

   A
1  hello
2  moon
3
4  rich
5  dells
6  cat

Give it a try and see how it works for you. Feel free to tweak it for your scenario.

  sub Stuff()

   Set rng = sht.UsedRange
    For Each cell In rng
        If cell.value = "text" then
         activesheet.EntireRow.Insert    
        End If
    Next cell

I think i might be best for your to just do a loop based on a column if the data is normalized.

try this

Sub test()
    Dim x&
    x = Cells(Rows.Count, "A").End(xlUp).Row
    While x <> 0
        If UCase(Cells(x, "A").Value) = UCase("string") Then
            Rows(x).Insert
        End If
    x = x - 1
    Wend
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM