excel - 在不移动单元格的情况下删除重复项
问题描述
我有一个包含两列的 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
解决方案
拆分单元格的值并在当前行上方查找通配符匹配项。
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
推荐阅读
- python - How to install Polynote on Windows?
- php - Laravel Cashier 10 - 条纹支付元素为空
- node.js - Feathers services usage and eslint
- python - django admin send back to homepage
- reactjs - Specify Next.js build directory in build command?
- html - 如何让固定元素在 100% 的 body 之后滚动?
- watchkit - 为什么我的 Xcode 11.2.1 (11B500)“Watch App”模板失败?
- javascript - 如何使用 jquery 从 HTML 中动态创建的表(带按钮)中获取某个表单输入的值?
- tensorflow - 如何将 keras.utils.Sequence 与多个文件一起使用
- javascript - 生成的 SHA256 哈希不适用于 PKCE OAuth2