如何使用 VBA 删除 Excel 宏中包含两列的重复项?

How to delete duplicates with two columns in a Excel macro using VBA?

我正在尝试创建一个 VBA 宏,其中要求用户从输入框到 select 范围列,如“A:A”。然后要求他们提供第二个列范围,例如“C:C”。

一旦select编辑了两个范围,我想让excel比较两个列范围的重复项并将它们从第一个范围中删除。

例如,如果用户select编辑了列范围 1 和列范围 2。并且都有编号为 5 和 7 的单元格,我希望列 range1 删除所有编号为 5 和 7 的单元格。

我写了一些 VBA 代码来根据我对你所做的事情的理解来执行这个操作。但是,我假设数据量相对较小并且对效率的需求不是很大。 另外,不用担心任何错误处理等问题

需要进行修改才能使它从头开始,以更稳健地运行。

选项显式

Sub DeleteDupValuesInFirstSelectedColumn() '例程要求用户 select 两个范围然后 ' 删除第一个列中重复的值 ' 在第二个范围内

Dim CWS As Worksheet
Dim SelRng As Range, Col1 As Range, Col2 As Range
Dim Cell1 As Range, Cell2 As Range

Set CWS = ActiveSheet

'Ask the user to select a range
Set SelRng = Application.InputBox( _
  Title:="Range 1 Selection", _
  Prompt:="Select the first column", _
  Type:=8)

'Limit the selection to the first column in the used range
Set Col1 = Intersect(CWS.UsedRange, SelRng.Columns(1).EntireColumn)

'Ask the user to select a second range
Set SelRng = Application.InputBox( _
  Title:="Range 2 Selection", _
  Prompt:="Select the second column", _
  Type:=8)

'Limit the selection again
Set Col2 = Intersect(CWS.UsedRange, SelRng.Columns(1).EntireColumn)

'Super inefficient. Relying on insignificant amounts of values
'Don't use loop within a loop for anything important
For Each Cell2 In Col2
    For Each Cell1 In Col1
        If Cell1.Value = Cell2.Value Then
            'If the correct cells are being filled, uncomment the line to delete
            Cell1.Interior.ColorIndex = 3
            'Cell1.Delete Shift:=xlUp
        End If
    Next Cell1
Next Cell2

结束子