[英]finding cell value and delete it in excel vba
I want to return the value of the cell it's found in VBA and clear all of it's content with another 3 rows below it as well, but I'm currently stuck.我想返回它在 VBA 中找到的单元格的值,并清除它下面的另外 3 行的所有内容,但我目前被卡住了。 I can find where the cell is coming from, but it's deleting the whole range instead of the specific range (I'm aware the
range("A7:H20")
was wrong).我可以找到单元格的来源,但它删除了整个范围而不是特定范围(我知道
range("A7:H20")
是错误的)。 How do I select the correct range?我如何使 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
You could just use cell.Clear
, or if you want the cell cleared and the next 3 below it use something like this你可以只使用
cell.Clear
,或者如果你想清除单元格并且下面的下一个 3 使用类似这样的东西
For i = 0 To 3
cell.Offset(i, 0).Clear
Next
Another solution: I am using a sub to which you pass the parameters:另一个解决方案:我正在使用一个你传递参数的子程序:
Furthermore I am looking from the bottom to the top of the range - otherwise cells could be cleared that contain the string to be found - and then below values won't get cleared:此外,我正在从范围的底部到顶部查看 - 否则可以清除包含要找到的字符串的单元格 - 然后将不会清除以下值:
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
I think you mean "return the address of that cell", no?我认为你的意思是“返回那个单元格的地址”,不是吗?
Debug.Print(cell.Address)
will get you this info. Debug.Print(cell.Address)
将为您提供此信息。 But you don't actually need it here.但你实际上并不需要它。 Instead of
Range("A7:H20").Clear
write cell.Resize(1 + i, 1).Clear
with i
= number of rows you want to clear along with cell
itself (no need for a loop).而不是
Range("A7:H20").Clear
write cell.Resize(1 + i, 1).Clear
with i
= 要清除的行数以及cell
本身(不需要循环)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.