如何通过单元格循环,并创build一个新的行,如果它包含一个特定的string在VBA?
我想通过内容遍历列A中的所有单元格,如果它包含特定的string,则在单元格上创build一个新行。 这是我到目前为止的代码:
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
任何想法,为什么这不起作用,以及如何解决它?
假设您的Excel工作表包含以下内容:
A 1 hello 2 moon 3 rich 4 dells 5 cat
你的macros不能正常工作的原因是因为你正在成功创build一个新行,然后macros立即下到下一行并find相同的匹配项,然后添加一个新的空行,然后进入下一行find相同的比赛…等等。
如果我们想在rich
行上面input一个新行,像这样的macros可能会更好:
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
试试看看它是如何为你工作的。 随意调整你的情况。
sub Stuff() Set rng = sht.UsedRange For Each cell In rng If cell.value = "text" then activesheet.EntireRow.Insert End If Next cell
我想我可能是最好的,只是做一个基于列的循环,如果数据正常化。
尝试这个
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