【问题标题】:How to look at two columns and delete duplicates in second column如何查看两列并删除第二列中的重复项
【发布时间】:2017-02-09 07:14:32
【问题描述】:

我正在尝试编写一个代码,让我可以查看两个非常相似的列,并清除第二列中重复的单元格(如果它已经存在于第一列中)。我有一个可以工作的代码,但它正在删除一些重复项并将它们向上移动,但我希望它们保留在原来的单元格中。我基本上希望它说“如果单元格存在于第 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

【问题讨论】:

  • 如果您希望它们保持原样,您需要循环并使用 Find 或 MATCH 来查看是否存在匹配项,如果找到匹配项则清除内容。
  • 你知道这样的示例代码是什么样子的吗?我还是 VBA 的新手,所以我不确定如何执行它。谢谢!!

标签: excel vba macros copy duplicates


【解决方案1】:

要执行 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

这会将 B 列中的重复项替换为空白,而不是删除/向上移动。

【讨论】:

    【解决方案2】:

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

    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 (i.e. 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 列“I”相关单元格(即不是空白单元格)

    • 不要进行不必要的复制和粘贴

    • 只在 Sheet2 中写入想要的值

    【讨论】:

    • 效果很好,谢谢!另一个快速的问题,说我必须不止一次这样做,我希望它再次检查更改的值但不删除背页中的任何历史 cmets,我可以添加一些只会复制新值的东西如果单元格为空,请从参考表中复制,如果不是,请将其复制到右侧的列等。再次感谢您!
    • 不客气。请按照本网站规则:1) 任何新问题都必须在新帖子中提出。它会帮助您展示您的代码和努力 2) 既然我完成了您的 original 问题,那么请将答案标记为已接受。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2020-09-17
    • 2017-06-05
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    相关资源
    最近更新 更多