VBA - 在列中查找多个字符串然后删除行

时间:2014-10-27 19:18:33

标签: excel vba excel-vba

以下VBA代码效果很好但是我想添加更多字符串来删除

例如酒店,住宅,公寓等最多50个值

编辑 - 位于C栏的值

我已经查看了数组,但仍无法找到解决方案

Dim Find As Range
Application.ScreenUpdating = False
Set Find = .Range("C:C").Find(what:="House")
Do Until Find Is Nothing
    Find.EntireRow.Delete
    Set Find = .Range("C:C").FindNext
Loop

1 个答案:

答案 0 :(得分:1)

删除循环中的行确实会降低代码的速度。将它们存储在临时范围内,然后一次性删除它。还要存储您想要在数组中找到的所有单词,然后遍历它以进行搜索。

试试这个(未经测试)。

Sub Sample()
    Dim sString As String
    Dim MyAr
    Dim i As Long
    Dim delRange As Range, aCell As Range
    Dim ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Sheet1")

    '~~> Add more to the list here separated by "/"
    sString = "Hotel/Home/Flat"

    MyAr = Split(sString, "/")

    With ws
        For i = LBound(MyAr) To UBound(MyAr)

            Set aCell = .Columns(3).Find(What:=MyAr(i), LookIn:=xlValues, _
            LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)

            If Not aCell Is Nothing Then
                If delRange Is Nothing Then
                    Set delRange = .Rows(aCell.Row)
                Else
                    Set delRange = Union(delRange, .Rows(aCell.Row))
                End If
            End If
        Next i
    End With

    If Not delange Is Nothing Then delRange.Delete
End Sub

以上示例仅搜索一个单词。如果要查找重复,请使用Findnext

替代.Find

将Autofilter与上面的数组一起使用。请参阅this链接。那会给你一个开始。