Excel VBA循环遍历列并根据单元格值插入行

时间:2021-05-31 12:13:15

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".

我正在尝试构建一个循环遍历C8:C3276范围内每个单元格的代码,如果单元格值为“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! :)

任何帮助是极大的赞赏! :)

1 个解决方案

#1


3  

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.

我认为有两个问题。 1)你应该向后循环,否则你将跳过行,因为你要添加更多的行,2)在你的循环中你应该引用单元格而不是从未设置的ActiveCell。

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

#1


3  

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.

我认为有两个问题。 1)你应该向后循环,否则你将跳过行,因为你要添加更多的行,2)在你的循环中你应该引用单元格而不是从未设置的ActiveCell。

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