2017-08-13 79 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 
相關問題