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

时间:2017-06-29 07:37:19

标签: excel vba excel-vba insert

我想找到包含精确值的单元格,并在这些单元格前面插入空白行。我已经有了代码,它会查找并插入这些行,但只在这些单元格后面。

代码在这里:

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

此代码将在所有单元格后面添加8行,其中包含单词“Workflow”,但我无法弄明白,如何将它们放在单元格“Workflow”前面

我想,当我把 - 而不是+,它应该解决它,但是当我以这种方式改变这条线时:

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

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

请问您的建议,我该怎么办?

非常感谢

1 个答案:

答案 0 :(得分:1)

而不是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