1

我正在尝试在包含特定单词的行上方插入一个空白行。但到目前为止,我只能将它插入到这一行下方。

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

4

1 回答 1

2

如果您使用 find 方法,它会更容易和更快(AFAIK)。

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

最后,作为一个好的做法,尝试将您的过程和变量命名为有意义的名称并缩进您的代码(您可以使用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

让我知道它是否有效。

于 2020-12-15T03:35:35.577 回答