Excel VBA代码,用于查找某个单元格并删除其周围的部分

Excel VBA代码,用于查找某个单元格并删除其周围的部分,vba,excel,Vba,Excel,我正在用Excel编写宏。部分代码查找包含“附加包装”的单元格,然后删除该单元格周围一组单元格的内容 以下是目前实现这一目标的代码: Cells.Find("Attached Packaging").Activate ActiveCell.Resize(2, 4).Select Selection.Clear ActiveCell.Offset(1, -1).Select Selection.Clear 我现在的问题是,出乎意料地,我有多个带有“附加包装”的单元格,这些单元格现在也必须删除 因

我正在用Excel编写宏。部分代码查找包含“附加包装”的单元格,然后删除该单元格周围一组单元格的内容

以下是目前实现这一目标的代码:

Cells.Find("Attached Packaging").Activate
ActiveCell.Resize(2, 4).Select
Selection.Clear
ActiveCell.Offset(1, -1).Select
Selection.Clear
我现在的问题是,出乎意料地,我有多个带有“附加包装”的单元格,这些单元格现在也必须删除

因此,总结一下:我需要修改这段代码,以便它在电子表格中找到所有“附加的打包”单元,并删除它们周围的组

Sub clearCells()
Dim ws As Worksheet
Dim lastrow As Long, currow As Long
Dim critvalue As String

Set ws = Sheets("Sheet1")

' Change A to a row with data in it
lastrow = ws.Range("A" & Rows.Count).End(xlUp).Offset(1).Row - 1

'Change 2 to the first row to check
For currow = 2 To lastrow
    critvalue = "Attached Packaging"

    ' Change A to the row you are looking in
    If ws.Range("A" & currow).Value = critvalue Then

        ' Use the currow to select the row and then create an offset
        ws.Range("A" & currow).offset("B" & currow - 1).clear
        ws.Range("A" & currow).offset("B" & currow + 1).clear

    End If
Next currow

End Sub

在我评论的地方进行必要的更改。它应该会起作用。

您假设critvalue只出现在A列中,我们不知道它是否为真。正如我在评论中提到的,你想使用find。find比查看每个单元格要好。
Sub clear()

Dim ws As Worksheet
Dim search As String
Dim f As Variant
Dim fRow As Long
Dim fCol As Long

search = "Attached Packaging"
Set ws = ThisWorkbook.Worksheets("Sheet4") 'change sheet as needed

With ws.Range("A1:AA1000") 'change range as needed
    Set f = .Find(search, LookIn:=xlValues)
    If Not f Is Nothing Then
        Do
            fRow = f.Row
            fCol = f.Column
            ws.Range(Cells(fRow, fCol), Cells(fRow + 1, fCol + 3)).clear
            ws.Cells(fRow + 1, fCol - 1).clear
            Set f = .FindNext(f)
        Loop While Not f Is Nothing
    End If
End With

End Sub