Copy row above the row containing certain text

2019-09-14 22:51发布

I have a code to copy the entire row if column B contains a certain text ("ACK-", but now I need to copy the entire row directly above the one with the certain text ("ACK-". Is this even possible? Any help will be appreciated.

Sub HEA_Filter()
Dim strArray As Variant
Dim wsSource As Worksheet
Dim wsDest As Worksheet
Dim NoRows As Long
Dim DestNoRows As Long
Dim I As Long
Dim J As Integer
Dim rngCells As Range
Dim rngFind As Range
Dim Found As Boolean

strArray = Array("ack-")

Set wsSource = ActiveSheet

NoRows = wsSource.Range("A65536").End(xlUp).Row
DestNoRows = 1
Set wsDest = Sheets("Real Alarms")

For I = 1 To NoRows

Set rngCells = wsSource.Range("B" & I)
Found = False
For J = 0 To UBound(strArray)
Found = Found Or Not (rngCells.Find(strArray(J)) Is Nothing)
Next J

If Found Then
rngCells.EntireRow.Copy wsDest.Range("A" & DestNoRows)

DestNoRows = DestNoRows + 1
End If
Next I
End Sub

标签: excel vba
1条回答
啃猪蹄的小仙女
2楼-- · 2019-09-14 23:52

To reference "the row above", you can use the Range.Offset method:

rngCells.Offset(-1).EntireRow.Copy wsDest.Range("A" & DestNoRows)
'       ^^^^^^^^^^^^

However, be aware that this raised a runtime error if the range is at row 1, because row 0 does not exist. You might want to add a check for it, for example:

If rngCells.Row > 1 Then rngCells.Offset(-1).EntireRow.Copy ...
查看更多
登录 后发表回答