使用VBA基于B列中的现有值从列A中删除重复项

时间:2017-04-30 09:00:22

标签: excel vba duplicates

我需要在A列和B列输入数据,并获取列A 但不在列B 中写入C列的数据。

我需要的例子:

picture1

picture2

2 个答案:

答案 0 :(得分:1)

稍微不同且更快的方法,如果没有循环通过工作表上的单元格,那就是......

Private Sub CommandButton1_Click()
Dim x, y(), dict
Dim i As Long, j As Long
x = Range("A1").CurrentRegion
Set dict = CreateObject("Scripting.Dictionary")
Columns("C").ClearContents
For i = 1 To UBound(x, 1)
    dict.Item(x(i, 2)) = ""
Next i
j = 1
For i = 1 To UBound(x, 1)
    If Not dict.exists(x(i, 1)) Then
        ReDim Preserve y(1 To j)
        y(j) = x(i, 1)
        j = j + 1
    End If
Next i
Range("C1").Resize(UBound(y), 1) = Application.Transpose(y)
End Sub

答案 1 :(得分:0)

将其放在工作表后面的代码文件中,并将CommandButton1更改为按钮名称。

Option Explicit

Private Sub CommandButton1_Click()

    Dim r As Range, matched_ As Variant, counter_ As Long

    'Loop in each cell in Column A
    For Each r In Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row)
        If Not IsEmpty(r) Then
            'Loop for a matching value in Column B
            matched_ = Application.Match(r.Value, Columns(2), 0)

            'If match not found, write the value in Column C
            If IsError(matched_) Then
                counter_ = counter_ + 1
                Range("C" & counter_) = r.Value
            End If
        End If
    Next r
End Sub