简体   繁体   中英

Excel VBA loop through column and insert rows based on cell value

Hello!

I am trying to build a code that loops through each cell in range C8:C3276 and inserts a new row below if the cell value is "Total".

Here is the code i have so far:

Sub Create_new_rows()

Dim rng As Range
Dim cell As Range
Set rng = Range("C8:C3276")

For Each cell In rng

If ActiveCell.Value = "Total" Then
ActiveCell.Offset(1, 0).Activate
ActiveCell.EntireRow.Insert
End If

Next cell

End Sub

Nothing happens when i execute the code. I assume the code is built incorrectly as the macro runs (i get no error message), but without doing anything.

Any help is greatly appreciated! :)

Two problems I think. 1) You should loop backwards as otherwise you will skip rows as you are adding more rows, and 2) in your loop you should have referred to cell rather than the ActiveCell which is never set.

Sub Create_new_rows()

Dim rng As Range, r As Long

Set rng = Range("C8:C3276")

For r = rng.Count To 1 Step -1
    If rng(r).Value = "Total" Then
        rng(r + 1).EntireRow.Insert
    End If
Next r

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