我想使用预先存在的 VBA 代码从列表中删除重复项

问题描述 投票:0回答:1

我正在寻找从数字列表中删除重复项。 这是代码。

Dim combined As String
lr = Cells(Rows.Count, 1).End(xlUp).Row
Range(Cells(lr, 1), Cells(lr, 35)).Select
i = lr
While i > 1
    If i = lr Then
    combined = Cells(i, 1).Value
    Else
      combined = Cells(i, 1).Value & ";" & combined
    End If
i = i - 1
Wend
Cells(1, 2).Value = combined
Cells(1, 2).Select
Cells(1, 2).Copy
End Sub
excel vba
1个回答
0
投票

您可以使用 Dictionary 对象。

初始化一个字典来存储列表中的唯一值,然后循环遍历列表中的每个值,检查它是否已存在于字典中。如果没有,请将 va 添加到字典中。然后将唯一值组合成以分号分隔的字符串并将其放入单元格中。

  Sub RemoveDuplicates()
     Dim dict As Object
     Set dict = CreateObject("Scripting.Dictionary")
     
     Dim lr As Long
     Dim i As Long
     Dim value As Variant
     Dim combined As String
     
     lr = Cells(Rows.Count, 1).End(xlUp).Row
     
     ' Loop through the range and add unique values to the dictionary
     For i = 1 To lr
        value = Cells(i, 1).Value
        If Not dict.exists(value) Then
              dict(value) = True
        End If
     Next i
     
     ' Combine unique values into a string
     combined = Join(dict.keys, ";")
     
     ' Output the combined string to a cell
     Cells(1, 2).Value = combined
  End Sub
© www.soinside.com 2019 - 2024. All rights reserved.