首页 > 解决方案 > 从列表中搜索数据并删除行

问题描述

我在 Sheet1 中有一张桌子。我需要在 Sheet1 中搜索 Sheet2-ColumnA 中的术语。

Sheet2-ColumnA 中的排除列表与 Sheet1 中的单元格内容不匹配,但在单元格内容中找到(例如:在“yellow;orange”或“orange;yellow”中找到“orange”)。

如果找到该条件,则删除该行。如果它没有找到条件,继续向下列表,直到它到达一个空单元格。

我记录了一轮,但我需要修改它以循环遍历整个排除列表,直到它到达排除列表中的一个空单元格。

Sub ExclusionList()
'
' ExclusionList Macro
' Find terms from exclusion list and delete row
'
' Go to sheet2 and select first term in exclusion list
    Sheets("Sheet2").Select
    Range("A1").Select

' Copy cell contents and find in sheet 1
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Find(What:="orange", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate

' Delete row if found
    Application.CutCopyMode = False
    Selection.EntireRow.Delete
End Sub

在此示例中,“橙色”是 Sheet2 A1 中的条件。如果可以跳过复制/粘贴并直接引用 Cells.Find() 函数中的排除列表,这似乎会清理代码并提高整体效率。

标签: excelvba

解决方案


尝试这个。

这是避免 Select/Activate的有用资源。这大大缩短了代码并使其更有效。

Sub ExclusionList()

Dim r As Range, rFind As Range

With Sheets("Sheet2")
    For Each r In .Range("A1", .Range("A" & Rows.Count).End(xlUp)) 'loop through every cell in sheet2 column A
        Set rFind = Sheets("Sheet1").Cells.Find(What:=r.Value, LookAt:=xlPart, MatchCase:=False, SearchFormat:=False)
        If Not rFind Is Nothing Then 'check that value is found to avoid error on next line
            rFind.EntireRow.Delete
        End If
    Next r
End With

End Sub

推荐阅读