2017-09-26 50 views
2

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中不使用循環?

+0

爲什麼你想在沒有循環的VBA中做到這一點? – jsheeran

+0

因爲我的數據太大,循環需要很多時間! – BlueFx

+0

您無法避免在此處循環,但可以通過對列A中的數據進行排序並執行二分搜索來縮短所需的時間。 – jsheeran

回答

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

+0

@BlueFx - 哎呀!我只是注意到你想要的解決方案而不使用循環 – Mrig

+0

是的,我想要的解決方案沒有使用循環,anw,感謝發佈 – BlueFx

+0

@BlueFx - 查看更新的答案。 – Mrig

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

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一點。

+0

感謝發佈,但我想純粹的VBA代碼的解決方案(我知道SQL或R可以做得更好) – BlueFx

+0

這是VBA!順便說一下,對於SO以外的其他人,回覆也應該是有趣的:-) –

相關問題