vba - 如何使用 VBA 在 Excel 中搜索单词然后删除整行?

标签 vba excel

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

    Columns("D:D").Select
    Cells.Find(What:="DR", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
        xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
        , SearchFormat:=False).Activate
Do 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"))

我很乐意为您提供帮助。

最佳答案

另一种方式(最快的方式)

假设您的工作表如下所示

enter image description here

您可以使用 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

输出:

enter image description here

关于vba - 如何使用 VBA 在 Excel 中搜索单词然后删除整行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19289229/

相关文章:

string - InStr 找不到子字符串

vba - Excel 将一系列单元格值复制到剪贴板

sql - 在 Sql 查询中使用单元格中的日期或命名范围

excel - 插入的字表不显示边框

vba - 将选择导出到 CSV

vba - 添加以单引号开头的字符串到excel单元格

excel - vba 插入验证列表 - 工作表锁定时出现错误 1004?

VBA方法excel根据值将单元格移动到其他行

Excel VBA如何在第一个匹配后找到下一个值

arrays - 从子例程返回数组给出 : Compile error: Can't assign to array