如何搜索包含“text”的特定列并删除不包含搜索的所有行

时间:2013-01-11 02:07:12

标签: arrays vba excel-vba excel

以下VBA代码是查找文本和删除行。但它是基于整张表进行搜索。

如何仅将搜索“特定列”并列出文本数组,删除包含文字的行

根据以下代码,搜索我不想要的整张表。

Sub DeleteSystemMessage()
    Dim varList As Variant
    Dim varQP As Variant
    Dim lngarrCounter As Long
    Dim rngFound As Range, rngToDelete As Range
    Dim strFirstAddress As String

    Application.ScreenUpdating = False


'delete system message
    varList = VBA.Array("XXXXXX", vbTextCompare)

    For lngarrCounter = LBound(varList) To UBound(varList)
        With Sheet1.UsedRange
            Set rngFound = .Find( _
                                What:=varList(lngarrCounter), _
                                Lookat:=xlWhole, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlNext, _
                                MatchCase:=False)

            If Not rngFound Is Nothing Then
                strFirstAddress = rngFound.Address

                If rngToDelete Is Nothing Then
                    Set rngToDelete = rngFound
                Else
                    If Application.Intersect(rngToDelete, rngFound.EntireRow) Is Nothing Then
                        Set rngToDelete = Application.Union(rngToDelete, rngFound)
                    End If
                End If

                Set rngFound = .FindNext(After:=rngFound)

                Do Until rngFound.Address = strFirstAddress
                    If Application.Intersect(rngToDelete, rngFound.EntireRow) Is Nothing Then
                        Set rngToDelete = Application.Union(rngToDelete, rngFound)
                    End If
                    Set rngFound = .FindNext(After:=rngFound)
                Loop
            End If
        End With
    Next lngarrCounter

    If Not rngToDelete Is Nothing Then rngToDelete.EntireRow.Delete
Application.ScreenUpdating = True


End Sub

1 个答案:

答案 0 :(得分:1)

如果您更改此类搜索代码,则只会搜索“A”列。

Set rngFound = Sheets(1).Columns("A:A").Find( _
                            What:=varList(lngarrCounter), _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlNext, _
                            MatchCase:=False)