[英]How do I loop through cells and create a new row if it contains a specific string in 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
知道为什么这不起作用以及如何解决它?
假设您的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
试一试,看看它是如何为您服务的。 随意调整它的方案。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.