最有效地根据组合框值评估列中的值列表

时间:2016-02-27 11:16:40

标签: excel vba

我正在尝试根据组合框中的值删除临时列表中的重复值。下面的代码循环遍历各行以检查值是否匹配。这很慢。

Dim ws As Worksheet
Dim i As Long

Set ws = Sheets("TempList3")

On Error Resume Next

For i = Cells(Rows.Count, 2).End(xlUp).Row To 1 Step -1
    If Cells(i, 2) <> Sheets("Sheet1").ComboBox2.Value Then
        ws.Rows(i).EntireRow.Delete
    End If
Next

有没有办法根据组合框的值评估整个列的值,然后删除工作表上的所有行。或许还有更好的方法?

2 个答案:

答案 0 :(得分:2)

我使用循环查找功能,它删除找到值的行,然后再次搜索并删除它找到的下一行,直到找不到工作表上的组合值:

std::cout << MakeObj(1).Me().member << std::endl;

答案 1 :(得分:1)

我不知道你说了多少行,我用了1万个代码。这里有两个例子,尝试两者,看看什么最适合你。

您可以遍历该列并对找到的范围进行工会化,然后删除行,例如。

See here for example workbook

Sub UnIonRng()
    Dim FrstRng As Range
    Dim UnIonRng As Range
    Dim c As Range, s As String

    s = Sheets("Sheet1").ComboBox2
    Set FrstRng = Range("B:B").SpecialCells(xlCellTypeConstants, 23)

    For Each c In FrstRng.Cells
        If c = s Then
            If Not UnIonRng Is Nothing Then
                Set UnIonRng = Union(UnIonRng, c)    'adds to the range
                'MsgBox UnionRng.Address    'remove later

            Else
                Set UnIonRng = c
            End If
        End If
    Next c

    UnIonRng.EntireRow.Delete
End Sub

或者您可以尝试过滤列B并删除行:

Sub FilterDeleteRow()
    Dim ws As Worksheet
    Dim LstRw As Long, Rng As Range, s As String, x

    Set ws = Sheets("TempList3")
    s = Sheets("Sheet1").ComboBox2

    Application.ScreenUpdating = 0

    With ws
        LstRw = .Cells(.Rows.Count, "B").End(xlUp).Row
        x = Application.WorksheetFunction.CountIf(.Range("B:B"), s)
        If x > 0 Then
            Columns("B:B").AutoFilter Field:=1, Criteria1:=s
            Set Rng = .Range("B2:B" & LstRw).SpecialCells(xlCellTypeVisible)
            Rng.EntireRow.Delete
            .AutoFilterMode = 0
        Else: MsgBox "Not Found"
        End If
    End With

End Sub