VBA – 在列中查找值并在这些单元格的前面插入空白行

我想find单元格,其中包含一个确切的值,并插入这些单元格前面的空白行。 我已经有了代码,它将查找并插入这些行,但只在这些单元格后面。

代码在这里:

Private Sub SearchnInsertRows() Dim LastRow As Long Dim rng As Range, C As Range Dim vR(), n As Long With Worksheets("INPUT_2") ' <-- here should be the Sheet's name LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' last row in column A Set rng = .Range("A1:A" & LastRow) ' set the dynamic range to be searched ' loop through all cells in column A and copy below's cell to sheet "Output_2" For Each C In rng If C.Value = "Workflow" Then .Range(Cells(C.Row + 1, 1), Cells(C.Row + 8, 8)).EntireRow.Insert End If Next C End With End Sub 

这段代码将在所有包含单词“Workflow”的单元格后面添加8行,但我无法弄清楚,如何将它们放在单元格“Workflow”

我想,当我把 – 而不是+,它应该解决它,但是当我这样改变这条线:

 .Range(Cells(C.Row - 1, 1), Cells(C.Row - 8, 8)).EntireRow.Insert 

并运行它,Excel将卡住,仍然添加行。

我可以问你一个build议吗,请问我做错了什么?

非常感谢

而不是一个For Each循环使用一个For i = LastRow to 1 Step -1循环从最后一行向后循环到第一个。 插入或删除行总是要倒退(从底部到顶部),因为那样只会影响已经处理过的行,否则未处理的行的行数将会改变并弄乱循环。

像下面的东西应该工作:

 Option Explicit 'Very first line in a module to enforce correct variable declaring. Private Sub SearchAndInsertRows() Dim lRow As Long, iRow As Long With Worksheets("INPUT_2") ' <-- here should be the Sheet's name lRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' last row in column A 'loop backwards (bottom to top = Step -1) through all rows For iRow = lRow To 1 Step -1 'check if column A of current row (iRow) is "Workflow" If .Cells(iRow, "A").Value = "Workflow" Then .Rows(iRow).Resize(RowSize:=8).Insert xlShiftDown 'insert 8 rows and move current (iRow) row down (xlShiftDown) 'means: insert 8 rows ABOVE current row (iRow) '.Rows(iRow + 1).Resize(RowSize:=8).Insert xlShiftDown 'alternatively use .Rows(iRow + 1) to insert BELOW current row (iRow) End If Next iRow End With End Sub