如何在单元格中查找值并将其删除?

时间:2017-08-13 07:06:30

标签: excel vba excel-vba

我想在某个范围内找到一个值,然后删除该值。

我找到了一些查找值的代码,但后来删除了其他单元格,而不是找到的值。

这是代码:

Private Sub CLEAROLD_Click()

'PURPOSE: Clear out all cells that do not contain a specific word/phrase

Dim Rng As Range
Dim cell As Range
Dim ContainWord As String

'What range do you want to search?
Set Rng = Range("AA2:AC25")

'sub for the word
shorttext = traintype1.Value & number1.Value

'What phrase do you want to test for?
ContainWord = shorttext 

'Loop through each cell in range and test cell contents
For Each cell In Rng.Cells    
    If cell.Find(ContainWord) Is Nothing Then cell.ClearContents  
Next cell

End Sub

我尝试更改if条件,但我无法让它发挥作用。

2 个答案:

答案 0 :(得分:2)

由于您使用For Each cell In Rng.Cells遍历Range的单元格,因此您可以直接将单元格的值与ContainWord进行比较。

替换:

If cell.Find(ContainWord) Is Nothing Then cell.ClearContents  

使用:

If cell.Value2 = ContainWord Then cell.ClearContents

答案 1 :(得分:1)

使用替换功能不会更快

 rng.Replace What:=shorttext, Replacement:="", LookAt:=xlWhole, _
               SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
               ReplaceFormat:=False