【问题标题】:Remove duplicates from column A based on existing values in column B using VBA使用 VBA 根据 B 列中的现有值从 A 列中删除重复项
【发布时间】:2017-09-28 00:24:46
【问题描述】:

我需要在 A 列和 B 列中输入数据,并将 A 列中但 B 列中没有的数据写入 C 列。

我需要的示例:

【问题讨论】:

  • P.S 我在 VBA 中需要这个,因为它将用于超过 10,000 个单元格的列表,并且公式会堵塞整个 excel。
  • 启动此类项目的方法是以宏格式列出步骤并仅使用注释,例如' Take one address from column A'search for it in column BIF found, skip to nextELSE write the name in column C。这样,您将拥有“代码”,这将使您陷入困境。一旦你遇到困难,你可以在这个网站上找到帮助。
  • 我照你说的做了,但没有卡住,运行命令什么也没做。

标签: excel vba duplicates


【解决方案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

【讨论】:

  • 确实快得多。如果您在 If Not dict.exists(x(i, 1))... 块内添加 dict.Item(x(i, 1)) = "",则 A 列中可能的重复项将不会滑入输出。
  • 我认为在 C 列中有重复项是 OP 的要求,因为 OP 已显示为所需的输出。这就是为什么 dict.item 没有包含在代码中的原因,因为它在 C 列中只有唯一的项目。:)
【解决方案2】:

将其放在工作表后面的代码文件中,并将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

【讨论】:

  • 你是神!谢谢!您是否需要对代码做任何事情才能将其放入 ActiveX 命令按钮中?
  • 将其放在工作表后面的代码文件中,如果名称不同,请更改 CommandButton1
  • 看起来如果A列中有重复项,它们都会出现在C中。
猜你喜欢
  • 2016-10-25
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多