基于半唯一ID字符串删除行

时间:2017-08-16 15:45:03

标签: excel vba

我有一系列半唯一ID,类似于以下内容:

XX123456/01
XX123456/02
XX123456/03
XX122222/01
XX122222/02
XX122222/03
XX155555/01
XX155555/05

长度始终相同,并且始终用分隔符拆分,后跟辅助唯一ID。

我想运行一列并删除行,只留下具有最​​大辅助唯一ID的行,例如:

XX123456/03
XX122222/03
XX155555/05

我需要采用什么样的逻辑?

我知道如何通过循环列并将每个ID添加到数组中来处理标准重复项,如果ID已经在数组中,则删除一行,但我不知道如何处理辅助唯一ID

1 个答案:

答案 0 :(得分:0)

如果这是一次性工作,没有VBA就可以更安全,更容易。如果必须使用VBA,可以执行以下操作:

Sub RowDelete()
  Dim Rng     As Range

  Set Rng = Range("C2") 'Change this to the column and cell where your data begins (below the header).
  Rng.Sort key1:=Rng, order1:=xlAscending 'Sorts your data in ascending order.

  'The For Loop below is a little ugly, but it tests the number to the left of the delimiter and finds
  'the largest value to the right of the delimiter. It fills a temp column 50 columns over with the value "DELETE".
  For i = 1 To Range("C2", Rng.End(xlDown)).Rows.Count
    If Left(Rng.Offset(i, 0).Value, 8) = Left(Rng.Offset(i - 1, 0).Value, 8) _
    And Right(Rng.Offset(i, 0).Value, 2) > Right(Rng.Offset(i - 1, 0).Value, 2) Then Rng.Offset(i - 1, 50).Value = "DELETE"
  Next i

  'Loops through the temp column and deletes the row if its value is "DELETE"
  For i = Range("C2", Rng.End(xlDown)).Rows.Count To 1 Step -1
    If Rng.Offset(i - 1, 50).Value = "DELETE" Then Rng.Offset(i - 1, 50).EntireRow.Delete
  Next i
End Sub

请记住,我不知道您项目的规模或重要性。我很快把它扔到一起,希望它可以让你深入了解如何解决这个问题。

相关问题