在包含单词 vba excel 的行之前插入行

Insert row before over a row containing a word vba excel

我想在包含特定单词的行上方插入一个空白行。但是到目前为止我只能把它插入到这一行下面。

Sub INSERTROW()
 Dim c As Range
 Dim lRow As Long
 lRow = 1
 Dim lRowLast As Long
 Dim bFound As Boolean
 With ActiveSheet
  lRowLast = .Cells(.Rows.Count, 1).End(xlUp).Row
  Do
   Set c = .Range("A" & lRow)
   If c.Value Like "*SEARCHED VALUE*" Then
    bFound = True
   ElseIf bFound Then
    bFound = False
    If c.Value <> "BLANKROW" Then
     c.EntireRow.Insert
     lRowLast = lRowLast + 1
     c.Offset(-1, 0).Value = "BLANKROW"
     c.Offset(-1, 0).Font.Color = RGB(0, 0, 0)
    End If
   End If
   lRow = lRow + 1
  Loop While lRow <= lRowLast + 1
 End With
End Sub

如果您使用 find 方法,它会更容易和更快(据我所知)。

看到我插入找到值的行,然后我用偏移函数引用前一行。

最后,作为一种好的做法,尝试将您的过程和变量命名为有意义的名称并缩进您的代码(您可以使用 www.rubberduckvba.com

Public Sub InsertRowBeforeWord()
    
    Dim findString As String
    findString = "*SEARCHED VALUE*"
    
    Dim lastRow As Long
    lastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row
    
    Dim searchRange As Range
    Set searchRange = ActiveSheet.Range("A1:A" & lastRow)
    
    Dim returnRange As Range
    
    Set returnRange = searchRange.Find(What:=findString, _
                            After:=searchRange.Cells(searchRange.Cells.Count), _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlNext, _
                            MatchCase:=False)

    If Not returnRange Is Nothing Then
        
        returnRange.Offset(0, 0).EntireRow.Insert
        returnRange.Offset(-1, 0).Value = "BLANKROW"
        returnRange.Offset(-1, 0).Font.Color = RGB(0, 0, 0)
        
    End If

End Sub

如果有效请告诉我。