首页 > 解决方案 > 在不移动单元格的情况下删除重复项

问题描述

我有一个包含两列的 Excel 表,一列包含计算机上的问题名称,另一列包含存在此问题的计算机的串联序列号。

Excel 工作表的重点是找到要优先解决的问题的最佳组合,即计算机园区中最常见的问题组合。

这是一个数据样本:

Issue          Serials
Dead SSD     SN0125;
Dead CPU     SN0125;SN0452;
Dead Screen  SN0785;SN0452;SN0125;
Dead Ram     SN0785;SN0452;SN0658;SN0125;SN0111

这意味着SN0125在我们修复了它的SSD之后可以重复使用,而SN0111在我们修复它的ram、屏幕、cpu和SSD之后可以重复使用。
序列的串联没有任何模式或顺序。

我想要,如果连续出现一个序列,它不应该出现在下面的行中,所以我得到这样的东西。

Issue          Serials
Dead SSD     SN0125;
Dead CPU     SN0452;
Dead Screen  SN0785;
Dead Ram     SN0658;SN0111;

我尝试遍历行并使用替换删除重复的序列,但最终得到空的序列单元格。
这是我尝试过的代码:

For i = 2 To las_row
    s1 = Cells(i, 2)

    For j = i To las_row
        'We look for the content of the previous row, inside the next and remove it
        s2 = Cells(j, 2)
        Cells(i, 2) = Replace(s1, s2, "")
    Next j
Next i

标签: excelvba

解决方案


拆分单元格的值并在当前行上方查找通配符匹配项。

Option Explicit

Sub prioritize()

    Dim m As Variant, arr As Variant, r As Long, i As Long, str As String

    With Worksheets("sheet1")

        For r = 2 To .Cells(.Rows.Count, "B").End(xlUp).Row
            'split the cell value on a semi-colon delimiter
            arr = Split(.Cells(r, "B").Value2, Chr(59))

            'look for a previous match
            For i = LBound(arr) To UBound(arr)
                m = Application.Match(Chr(42) & arr(i) & Chr(42), .Columns("B"), 0)
                If m < r Then arr(i) = vbNullString
            Next i

            'put the array back together then repair it and put it into the cell
            str = Join(arr, Chr(59))
            Do While InStr(1, str, Chr(59) & Chr(59)) > 0: str = Replace(str, Chr(59) & Chr(59), Chr(59)): Loop
            Do While Left(str, 1) = Chr(59): str = Mid(str, 2): Loop
            Do While Right(str, 1) = Chr(59): str = Left(str, Len(str) - 1): Loop
            .Cells(r, "B") = str
        Next r

    End With
End Sub

在此处输入图像描述


推荐阅读