值列在一列中但不在其他列中

时间:2017-09-26 07:33:42

标签: excel vba

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

$res=mysqli_query($conn,$sql);
$rows=mysqli_affected_rows($conn);
if($rows!=0)
{
  echo "Record inserted";
}

现在我需要结果包含B列中的那些值,但不包含在A列中。我知道我可以使用CountIf来解决问题。但是,有没有办法在没有循环的情况下在VBA中完成它?

3 个答案:

答案 0 :(得分:2)

尝试使用以下公式, 在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 enter image description here

答案 1 :(得分:0)

试试这个:

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

enter image description here

答案 2 :(得分:0)

只是为了好玩(和速度),你也可以用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。