如何查看两列并删除第二列中的重复项

我想写一个代码,让我看看两个非常相似的列,并清除第二列中重复的单元格,如果它已经存在于第一列。 我有一个工作的代码,但它删除了一些重复,并向上移动,但我希望他们留在原来的单元格。 我基本上想要说“如果单元格存在于第1列和第2列,请清除第2列中的单元格”。 我不确定这是否可能。 这是我一直在使用的代码。 任何帮助将不胜感激!

Sub CopyPasteHistorical() CopyPasteHistorical Macro Sheets("Sheet1").Select Columns("I:I").Select Selection.copy Sheets("Sheet2").Select Columns("D:D").Select ActiveSheet.Paste 'remove duplicates Columns("C:D").Select Dim duplicates As Range Set duplicates = Selection Selection.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes End Sub 

我会采取相反的方式,如下面(注释)的代码:

 Option Explicit Sub CopyPasteHistorical() Dim sht1Rng As Range, cell As Range With Worksheets("Sheet1") '<-- reference Sheet1 Set sht1Rng = .Range("I1", .Cells(.Rows.Count, "I").End(xlUp)).SpecialCells(xlCellTypeConstants) '<-- set range with its column "I" cells containing constant (ie not formulas) values End With With Worksheets("Sheet2") '<-- reference Sheet2 For Each cell In sht1Rng '<-- loop through Sheet1 range If cell.Value <> .Cells(cell.Row, "C") Then .Cells(cell.Row, "D") = cell.Value '<-- if sheet1 current cell content is different from Sheet2 column "C" cell content in the same row then write it in Sheet 2 column "D" corresponding row Next cell End With End Sub 

这样你:

  • 只打扰与Sheet1列“我”相关细胞(即不是空白的)

  • 不要做不必要的复制和粘贴

  • 只在Sheet2中写入想要的值

要做Scott正在谈论的事情,你可以尝试以下方法:

 Sub Test() Dim wb As Workbook Set wb = ThisWorkbook Dim ws As Worksheet Set ws = wb.Sheets("Sheet1") 'get the last row of the 1st column, "A" in this case Dim lastRow As Integer lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row Dim i As Integer 'loop through all the rows of column A For i = 1 To lastRow 'get value of cell, find and replace with "" in column "B" Dim curVal curVal = ws.Range("A" & i).Value ws.Columns("B").Replace _ What:=curVal, Replacement:="", _ SearchOrder:=xlByColumns, MatchCase:=True Next i End Sub 

这将用空白replaceB列中的重复项,而不是删除/向上移动。