如果在vba中包含特定字符串,我如何循环遍历单元格并创建新行?

时间:2015-05-08 01:55:57

标签: excel vba excel-vba

我想循环遍历A列中包含内容的所有单元格,如果它包含特定字符串,则在单元格上方创建一个新行。这是我到目前为止的代码:

 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

知道为什么这不起作用以及如何解决它?

3 个答案:

答案 0 :(得分:3)

假设您的Excel表格包含以下内容:

   A
1  hello
2  moon
3  rich
4  dells
5  cat

你的宏没有按预期工作的原因是因为你成功创建了一个新行,然后宏立即下降到下一行并找到相同的匹配,并添加一个新的空行,然后转到下一行并找到相同的匹配......以及之后。

如果我们想在rich的行上方输入一个新行,那么这样的宏可能效果更好:

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

运行之后,输出将如下所示:

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

试试看看它是如何运作的。随意为您的场景调整它。

答案 1 :(得分:0)

  sub Stuff()

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

我认为如果数据规范化,我可能最好只根据列进行循环。

答案 2 :(得分:0)

试试这个

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