Excel-如果特定列中的单元格包含在另一列中找到的值,则删除行

时间:2018-04-25 17:45:28

标签: excel vba excel-formula

如果在另一列中找到Vendor列中的值,我想删除所有行。 (另一张表中的lookupVendor Col)

enter image description here

MainSheet

LookupColumn

VendorCol
google 
microsoft
apple
vendorA
VendorB

这是我所拥有的,但它只删除了一个值。 如何使用整个LookupColumn并检测在lookupColumn中找到colc值的任何行。 我的简单VBA代码一次处理一个值。(效率不高)

Sub Find_Vendor()
    Dim rng As Range
    Dim what As String
    what = "Microsoft"
    Do
        Set rng = ActiveSheet.UsedRange.Find(what)
        If rng Is Nothing Then
            Exit Do
        Else
            Rows(rng.Row).Delete
        End If
    Loop
End Sub

Mainsheet:包含600,000行 LookupColumn包含400个条目。 对于我拥有的数据量,现有代码速度非常慢。

1 个答案:

答案 0 :(得分:1)

使用AutoFilter():

Option Explicit

Public Sub Find_Vendor()
    Dim filters As Variant
    With Sheets("LookupColumnSheet") ' change "LookupColumnSheet" to your actual sheet with lookup values name
        filters = Application.Transpose(.Range("A1", .Cells(.Rows.Count, 1).End(xlUp)).Value) ' collect "LookupColumnSheet" sheet column A values from row 1 down to last not empty row
    End With

    With Sheets("MainSheet") 'reference "MainSheet" sheet (change "MainSheet" to your actual "MainSheet" sheet name
        With .Range("C1", .Cells(.Rows.Count, 3).End(xlUp)) ' reference referenced sheet column C cells from row 1 down to last not empty one
            .AutoFilter Field:=1, Criteria1:=filters, Operator:=xlFilterValues ' filter referenced range with values from "LookupColumnSheet" sheet column A
            If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Delete ' if any filtered cells other than header then delete their entire row
        End With
        .AutoFilterMode = False ' remove filters
    End With
End Sub