【问题标题】:Excel [VBA] find duplicate data and delete the oldest oneExcel [VBA] 查找重复数据并删除最旧的数据
【发布时间】:2015-07-23 00:28:19
【问题描述】:

我在 MS Excel 中遇到问题。我有一个包含如下数据的电子表格:

 Name     |     timestamp
 ------------------------
 Smith    | 12.05.2015
 Smith    | 01.01.2015
 Smith    | 10.05.2015
 Simpson  | 14.04.2015
 Simpson  | 10.02.2015
 Simpson  | 21.03.2015
 Simpson  | 02.01.2015

我拥有的数据更大更复杂,并且存在具有不同时间戳的重复数据。现在我想删除旧的并想要这样的输出:

 Name     |     timestamp
 Smith    | 12.05.2015
 Simpson  | 14.04.2015

我知道如何删除重复项,但在这种情况下它有点不同。希望您能帮我解决问题。

【问题讨论】:

  • 这将使您开始1 将您的数据传输到数组2 在col Name 中创建一个唯一的数据集合,然后遍历该数组以获取最新时间。 3 将输出存储在数组中 4 将数组输出到工作表中
  • THIS 将帮助您开始
  • 你的时间戳是文本格式的吗?
  • 不,它的格式是日期
  • 这就是我的想法,但它不像我系统上的日期,可能是因为我正在使用 dd/mm/yyyy 并且它没有看到“。”句点作为日期分隔符。

标签: vba excel


【解决方案1】:

您可能不需要 VBA。

根据我的经验,Excel Remove Duplicates 代码可以删除列表中第一个遇到的重复项。

因此,按名称升序和时间戳降序对数据进行排序,然后仅从名称字段中删除重复项。

您应该保留最新的姓名。

【讨论】:

  • 错误答案。当您有多个时间戳时,Remove Duplicates 不会删除任何重复项,因为没有任何重复项。请参考问题中的示例数据。问题说他想要最新时间戳的记录
  • @SiddharthRout,对不起,你错了。我说从名称字段中删除重复项而不是两个字段。
  • 这又是一种错误的方式。那会有什么不同呢? :)
  • 我认为你误解了这个问题。 OP 不想要的只是名字。他也想要相应的时间戳:) 建议重新阅读问题
  • 抱歉,我应该说排序名称升序和日期/时间降序。如果您有两列数据,并且您在功能区的数据选项卡中选择删除重复项并取消选择第二列,则仅删除第一列中的重复项。尝试在 col A 中使用 Name 标题,在 col B 中使用 Time 标题;将您的姓名放在名称标题下方的单元格中;在时间标题正下方的单元格中输入 0:01;向下拖动几行;如前所述排序;转到数据>删除重复项; 取消选中时间列并点击确定。
【解决方案2】:

我做了一些测试,Range.RemoveDuplicates 似乎保留了每个重复值的第一个条目(至少在您将要使用的排序范围内)。这是我的解决方案:

Sub SortAndCondense()
'This subroutine sorts a table by name and secondarily by descending date.  It then removes
'all duplicates in the name column.  By sorting the dates in descending order, only the most
'recent entries for each name are preserved
Dim wrkSht As Worksheet
Set wrkSht = ThisWorkbook.Worksheets("Sheet1")
Dim dateTable As Range
Dim header1 As Range, header2 As Range
Set dateTable = wrkSht.Range("A2:B7") 'insert your actual table range; modify as necessary for column headers
Set header1 = wrkSht.Range("A2")
Set header2 = wrkSht.Range("B2")

'sort the column primarily by name, and secondarily by descending date.  The order in which the names are sorted
'is irrelevant.
dateTable.Sort Key1:=header1, Key2:=header2, Order2:=xlDescending

'remove all duplicate names.  The way remove duplicates works (so far as I can tell) is that it keeps only the
'topmost entry for each duplicate column.
dateTable.RemoveDuplicates 1
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多