查找单元格值并将其删除 excel vba

finding cell value and delete it in excel vba

我想 return 它在 VBA 中找到的单元格的值,并清除它下面的另外 3 行的所有内容,但我目前被卡住了。我可以找到单元格的来源,但它删除的是整个范围而不是特定范围(我知道 range("A7:H20") 是错误的)。我如何 select 正确的范围?

Sub Find_and_remove()
  For Each cell In Range("A7:H20")
    If cell.Value = Range("Q5") Then
      'return the range of that cell and deleted it with 3 row below it'
      Range("A7:H20").Clear
    End If
  Next cell
End Sub

您可以只使用 cell.Clear,或者如果您希望清除单元格并且下面的 3 个单元格使用类似这样的方法

For i = 0 To 3
    cell.Offset(i, 0).Clear
Next
Sub Find_and_remove()
Dim rng As Range

For Each rng In Range("A7:H20")
    If rng.Value = Range("Q5") Then Range(rng, rng.Offset(3, 0)).Clear
Next cell

End Sub

我想你的意思是“return那个单元格的地址”,不是吗? Debug.Print(cell.Address) 将为您提供此信息。但你实际上并不需要它。而不是 Range("A7:H20").Clearcell.Resize(1 + i, 1).Cleari = 您要清除的行数以及 cell 本身(不需要循环)。

另一个解决方案: 我正在使用一个你传递参数的 sub:

  • 要找到的值
  • 查看和清除内容的范围
  • 要清除的低于找到的值的行数。

此外,我正在从范围的 底部到顶部 查找 - 否则可能会清除包含要找到的字符串的单元格 - 然后将无法获得以下值已清除:

Option Explicit

'>>> example of how to call the findAndRemove-Sub <<<

Public Sub test_FindAndRemove()

With ActiveSheet   ' adjust this to your needs
    findAndRemove .Range("Q5"), .Range("A7:H20"), 3
End With

End Sub


'>>>> this is the sub that is doing the work <<<<<

Public Sub findAndRemove(strFind As String, _
    rgLookup As Range, _
    cntDeleteRowsBelow As Long)

Dim i As Long, c As Range

'start from the bottom and go up
'otherwise you could delete further strFind-cells unintentionally
For i = rgLookup.Rows.Count To 1 Step -1
    For Each c In rgLookup.Rows(i).Cells
        If c.Value = strFind Then
            'ATTENTION:
            'at this point there is no check if below row contains the strFind-value!
            c.Resize(cntDeleteRowsBelow + 1).Clear
        End If
    Next
Next

End Sub