[英]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.