Excel VBA:删除单个单元格

时间:2018-04-14 09:50:54

标签: excel vba excel-vba

我需要在VBA中创建Excel函数的最有效方法,即删除单元格中的重复项:

输入单元格(A1)应包含如下文本:

  

" First_element,Second_element,Third_element,Second_element,Fourth_element"

我需要一个如下公式:

  

= REMOVEDUPLICATES(A1)

在B2中产生以下输出:

  

" First_element,Second_element,Third_element,Fourth_element"

重要的是每个元素后跟逗号和空格","除了最后的元素。

1 个答案:

答案 0 :(得分:5)

尝试此功能

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