简体   繁体   English

检查单元格是否包含“特定单词”然后删除行

[英]check if cells contain “specific word” then delete row

I tried the code but it still unable to delete the cells which contains DNP. 我尝试了代码,但仍然无法删除包含DNP的单元格。 Is there something wrong with the code? 代码有问题吗? Thank you 谢谢

'Check to see if column contains dnp then delete row '检查列是否包含dnp然后删除行

Last = wsInput.Range("H" & Rows.Count).End(xlUp).Row
For iCntr = Last To 3 Step -1
If InStr(1, wsInput.Cells(iCntr, "H"), "dnp", vbTextCompare) = "[dnp]"Then 

         wsInput.Cells(iCntr, "H").EntireRow.Delete
    End If
Next iCntr

Create a range then do 1 delete, much better than multiple deletes. 创建一个范围然后执行1次删除,比多次删除要好得多。

Sub Temp()
Dim DelRange As Range, iCntr  as Long
For iCntr = 3 to Range("H" & Rows.Count).End(xlUp).Row
    If InStr(1, Range("H" & iCntr).Text, "dnp", vbTextCompare) > 0 Then
        If DelRange Is Nothing Then
            Set DelRange = Range("H" & iCntr)
        Else
            Set DelRange = Union(DelRange, Range("H" & iCntr))
        End If
    End If
Next iCntr
If Not DelRange Is Nothing Then DelRange.EntireRow.Delete
End Sub

The reason yours wasn't working is because Instr returns a numeric showing the position in the first string that the second string was found. 您的工作原因是因为Instr返回一个数字,显示第一个字符串中找到第二个字符串的位置。 If it finds the string it will return something >0 if it doesn't it will return 0 如果它找到了字符串,它将返回> 0,如果不是,它将返回0

If you want to do it without looping the range (which will be faster) you can use Find like this: 如果你想在没有循环范围的情况下(这将更快),你可以使用像这样的Find

Sub temp2()
Dim FoundCell As Range, LastCell As Range, DelRange As Range, FirstAddr As String
Set LastCell = Range("H" & Rows.Count)
Set FoundCell = Range("H:H").Find(what:="dnp", after:=LastCell)
Set DelRange = FoundCell
If Not FoundCell Is Nothing Then FirstAddr = FoundCell.Address
Do Until FoundCell Is Nothing
    Set FoundCell = Range("H:H").FindNext(after:=FoundCell)
    Set DelRange = Union(DelRange, FoundCell)
    If FoundCell.Address = FirstAddr Then Exit Do
Loop
If Not DelRange Is Nothing Then DelRange.EntireRow.Delete
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM