简体   繁体   English

Excel VBA:删除单个单元格中重复项的功能

[英]Excel VBA: Function that removes duplicates in a single cell

I need the most efficient way to create an Excel function in VBA that removes the duplicates in a cell: 我需要最有效的方法在VBA中创建Excel函数,以删除单元格中的重复项:

The input cell (A1) should contain a text like that: 输入单元格(A1)应包含如下文本:

"First_element, Second_element, Third_element, Second_element, Fourth_element" “第一要素,第二要素,第三要素,第二要素,第四要素”

I need a formula such as: 我需要一个公式,例如:

= REMOVEDUPLICATES(A1) = REMOVEDUPLICATES(A1)

That produces the following output in B2: 在B2中产生以下输出:

"First_element, Second_element, Third_element, Fourth_element" “第一要素,第二要素,第三要素,第四要素”

It is important that every element is followed by a comma-and-space ", " except the final element. 重要的是,除最后一个元素外,每个元素后面都必须有一个逗号和空格“,”。

Try this function 试试这个功能

Function RemoveDuplicates(inp As String)
Dim dict As Object
Const DELIMITER = ","
    Set dict = CreateObject("Scripting.Dictionary")

    Dim vdat As Variant
    vdat = Split(inp, DELIMITER)

    Dim i As Long
    For i = LBound(vdat) To UBound(vdat)

        If dict.Exists(vdat(i)) Then
        Else
            dict.Add vdat(i), vdat(i)
        End If
    Next i

    vdat = dict.Keys
    RemoveDuplicates = Join(vdat, DELIMITER)

End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM