簡體   English   中英

檢查單元格是否包含“特定單詞”然后刪除行

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

我嘗試了代碼,但仍然無法刪除包含DNP的單元格。 代碼有問題嗎? 謝謝

'檢查列是否包含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

創建一個范圍然后執行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

您的工作原因是因為Instr返回一個數字,顯示第一個字符串中找到第二個字符串的位置。 如果它找到了字符串,它將返回> 0,如果不是,它將返回0

如果你想在沒有循環范圍的情況下(這將更快),你可以使用像這樣的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