簡體   English   中英

查找單元格值並將其刪除 excel vba

[英]finding cell value and delete it in excel vba

我想返回它在 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
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

你可以只使用cell.Clear ,或者如果你想清除單元格並且下面的下一個 3 使用類似這樣的東西

For i = 0 To 3
    cell.Offset(i, 0).Clear
Next

另一個解決方案:我正在使用一個你傳遞參數的子程序:

  • 有待發現的價值
  • 查看和清除內容的范圍
  • 低於找到的值的行數將被清除。

此外,我正在從范圍的底部到頂部查看 - 否則可以清除包含要找到的字符串的單元格 - 然后將不會清除以下值:

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

我認為你的意思是“返回那個單元格的地址”,不是嗎? Debug.Print(cell.Address)將為您提供此信息。 但你實際上並不需要它。 而不是Range("A7:H20").Clear write cell.Resize(1 + i, 1).Clear with i = 要清除的行數以及cell本身(不需要循環)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM