如何在Excel中使用VBAsearch单词,然后删除整行?

有人请帮忙。 我试图写一个VBA代码,在我的Excel工作表列“D”中search特定的单词“DR”,然后删除整个行。 工作表中特定单词的出现次数很多。 我想要做的就是search这些出现,然后删除包含这些单词的整个行。 我的问题是,我不知道使用什么循环结构。 以下是我正在使用的代码。

    列( “d:d”)select
     Cells.Find(What:=“DR”,After:= ActiveCell,LookIn:= xlFormulas,LookAt:= _
         xlPart,SearchOrder:= xlByRows,SearchDirection:= xlNext,MatchCase:= False _
         ,SearchFormat:= False).Activate 
做 Cells.Find(What:=“DR”,After:= ActiveCell,LookIn:= xlFormulas,LookAt:= _ xlPart,SearchOrder:= xlByRows,SearchDirection:= xlNext,MatchCase:= False _ ,SearchFormat:= False).Activate

ActiveCell.EntireRow.Delete Loop While (Cells.Find(What:="DR"))

我会很乐意提供协助。

清洁和简单,伎俩! ;)

 LastRow = Cells(Rows.Count, "D").End(xlUp).Row For i = LastRow To 1 Step -1 If Range("D" & i).Value = "DR" Then Range("D" & i).EntireRow.Delete End If Next i 

另一种方式( 最快的方式

假设你的工作表看起来像这样

在这里输入图像说明

您可以使用Excel来完成肮脏的工作;)使用.AutoFilter

看到这个代码

 Sub Sample() Dim ws As Worksheet Dim lRow As Long Dim strSearch As String '~~> Set this to the relevant worksheet Set ws = ThisWorkbook.Worksheets("Sheet1") '~~> Search Text strSearch = "DR" With ws '~~> Remove any filters .AutoFilterMode = False lRow = .Range("D" & .Rows.Count).End(xlUp).Row With .Range("D1:D" & lRow) .AutoFilter Field:=1, Criteria1:="=*" & strSearch & "*" .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With '~~> Remove any filters .AutoFilterMode = False End With End Sub 

输出:

在这里输入图像说明

另外一种方法使用查找…

 Sub TestDeleteRows() Dim rFind As Range Dim rDelete As Range Dim strSearch As String Dim sFirstAddress As String strSearch = "DR" Set rDelete = Nothing Application.ScreenUpdating = False With Sheet1.Columns("D:D") Set rFind = .Find(strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchDirection:=xlNext, MatchCase:=False) If Not rFind Is Nothing Then sFirstAddress = rFind.Address Do If rDelete Is Nothing Then Set rDelete = rFind Else Set rDelete = Application.Union(rDelete, rFind) End If Set rFind = .FindNext(rFind) Loop While Not rFind Is Nothing And rFind.Address <> sFirstAddress rDelete.EntireRow.Delete End If End With Application.ScreenUpdating = True End Sub 

下面的例子是相似的,但它从底部开始,以相反的顺序到达顶部。 它一次删除每一行,而不是一次删除所有行。

 Sub TestDeleteRows() Dim rFind As Range Dim rDelete As Range Dim strSearch As String strSearch = "DR" Set rDelete = Nothing Application.ScreenUpdating = False With Sheet1.Columns("D:D") Set rFind = .Find(strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchDirection:=xlPrevious, MatchCase:=False) If Not rFind Is Nothing Then Do Set rDelete = rFind Set rFind = .FindPrevious(rFind) If rFind.Address = rDelete.Address Then Set rFind = Nothing rDelete.EntireRow.Delete Loop While Not rFind Is Nothing End If End With Application.ScreenUpdating = True End Sub