2017-08-13 78 views
0

我想查找范围内的值,然后删除该值。如何在单元中查找值并删除它?

我发现了一些代码,它寻找的值,但然后删除其他单元格,而不是找到的值。

这是代码:

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条件,但我不能让它工作。

+0

你做什么样的变化? (没有起作用的更改) – jsotola

+0

在问题标题中没有必要只使用大写字母。 – trincot

回答

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 
+0

THX现在工作。所以问题是我没有使用新的价值空间(如果)权利 –

+1

谢谢:我做到了 –

1

岂不是更快地使用替换功能

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