如何删除单元格中的重复单词?

时间:2019-02-28 15:39:41

标签: excel vba

我正在尝试删除单元格中的重复单词。例如,在单元格A1中,我具有以下内容:

"BOX TIL Rank Fifth TIL Over 01"

我正在尝试找出一种方法,使excel可以查看此单元格并删除第二个"TIL",因此它看起来像这样:

"BOX TIL Rank Fifth Over 01"

我试图不仅在一个单元格中,而且在整个单元格中都这样做。另一个问题是,例如某些单元格具有更长的字符串,一个看起来可能类似于上面的字符串,但是另一个可能像这样:

"BOX TIL Seventeen TIL COMM 03"

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

您需要遍历单元格并使用以下功能删除重复的单词。

Public Function RemoveDuplicateWords(InputString As String) As String
    Dim InputArray() As String
    InputArray = Split(InputString, " ")

    Dim DictUnique As Object
    Set DictUnique = CreateObject("Scripting.Dictionary")

    Dim OutputString As String

    Dim Word As Variant
    For Each Word In InputArray
        If Not DictUnique.Exists(Word) Then
            DictUnique.Add Word, 1
            OutputString = OutputString & " " & Word
        End If
    Next Word

    RemoveDuplicateWords = Trim$(OutputString)
End Function

该功能如何工作?

  • 它将字符串按空格分割成一个数组
  • 它使用字典来检查单词是否唯一
  • 如果该单词不在词典中,但已添加到OutputString,则不会将重复的单词添加到OutputString

您甚至可以将其用作公式

=RemoveDuplicateWords(A1)

enter image description here

答案 1 :(得分:1)

选择要处理的单元并运行此简短的VBA宏:

Sub RemoveDups()
    Dim r As Range, s As String, arr
    Dim c As Collection

    For Each r In Selection
        Set c = New Collection
        arr = Split(r.Value, " ")
        For i = LBound(arr) To UBound(arr)
            On Error Resume Next
                c.Add arr(i), CStr(arr(i))
            On Error GoTo 0
        Next i

        s = ""
        For i = 1 To c.Count
            s = s & " " & c.Item(i)
        Next i
        If Left(s, 1) = " " Then s = Mid(s, 2)
        r.Value = s
    Next r
End Sub

之前:

enter image description here

及之后:

enter image description here