Excel 值在一列中,但不在另一列中

Excel 值在一列中,但不在另一列中,excel,vba,Excel,Vba,VBA问题:我在excel中有两列: A B 10 6 5 1 6 4 2 7 8 9 4 8 9 10 7 5 3 11 现在我需要结果包含B列中的值,而不是A列中的值。我知道我可以使用CountIf来解决这个问题。但是,有没有任何方法可以在VBA中不循环地执行此操作?尝试以下方法: Sub Demo() Dim ws As Worksheet Dim cel As Range, rngA As Range, rngB As

VBA问题:我在excel中有两列:

A   B
10  6
5   1
6   4
2   7
8   9
4   8
9   10
7   5
    3
    11
现在我需要结果包含B列中的值,而不是A列中的值。我知道我可以使用CountIf来解决这个问题。但是,有没有任何方法可以在VBA中不循环地执行此操作?

尝试以下方法:

Sub Demo()
    Dim ws As Worksheet
    Dim cel As Range, rngA As Range, rngB As Range
    Dim lastRowA As Long, lastRowB As Long
    Application.ScreenUpdating = False

    Set ws = ThisWorkbook.Sheets("Sheet3")  'change Sheet3 to your data range

    With ws
        lastRowA = .Cells(.Rows.Count, "A").End(xlUp).Row   'last row with data in Column A
        lastRowB = .Cells(.Rows.Count, "B").End(xlUp).Row   'last row with data in Column B
        Set rngA = .Range("A2:A" & lastRowA)                 'range with data in Column A
        Set rngB = .Range("B2:B" & lastRowB)                 'range with data in Column B

        .Range("C2").Formula = "=IF(COUNTIF(" & rngA.Address & ",$B2)=0,B2,"""")"   'enter formula in Cell C2
        .Range("C2").AutoFill Destination:=.Range("C2:C" & lastRowB)                'drag formula down
        .Range("C2:C" & lastRowB).Value = .Range("C2:C" & lastRowB).Value           'keep only values
        .Range("C2:C" & lastRowB).SpecialCells(xlCellTypeBlanks).Delete Shift:=xlUp 'delte blank rows
    End With
    Application.ScreenUpdating = True
End Sub
试试下面的公式, 在D2中放置以下公式,选择D2到D11,然后按CTRL+D

=IF(ISNA(MATCH(B2,A:A,0))=TRUE,B2 & " Not Exist in Column A", B2 & " Exist in Column A")
OP

为了好玩(和速度),您还可以使用SQL:

Sub SqlSelectExample()
'list elements in col C not present in col B
    Dim con As ADODB.Connection
    Dim rs As ADODB.Recordset
    Set con = New ADODB.Connection
    con.Open "Driver={Microsoft Excel Driver (*.xls)};" & _
           "DriverId=790;" & _
           "Dbq=" & ThisWorkbook.FullName & ";" & _
           "DefaultDir=" & ThisWorkbook.FullName & ";ReadOnly=False;"
    Set rs = New ADODB.Recordset
    rs.Open "select ccc.test3 from [Sheet1$] ccc left join [Sheet1$] bbb on ccc.test3 = bbb.test2 where bbb.test2 is null  ", _
            con, adOpenStatic, adLockOptimistic
    Range("g10").CopyFromRecordset rs   '-> returns values without match
    rs.MoveLast
    Debug.Print rs.RecordCount          'get the # records
    rs.Close
    Set rs = Nothing
    Set con = Nothing
End Sub

您将不得不重新编写SQL。

为什么要在VBA中执行此操作而不进行循环?因为我的数据太大,循环占用了太多时间!您无法避免在此处循环,但可以通过对A列中的数据进行排序并进行二进制搜索来减少所需的时间。@BlueFx-Oops!我刚刚注意到你想要不使用循环的解决方案。是的,我想要不使用循环的解决方案,嗯,谢谢发布完美,它缩短了所需时间的一半,谢谢,MrigThank发布,但我想要纯VBA代码的解决方案(我知道SQL或R可以做得更好)这是VBA!顺便说一句,除了OP之外,SO上的回复对其他人来说也应该是有趣的:-)