Excel 2013 - 如何从单个单元格中删除重复的短语

时间:2015-08-10 23:19:16

标签: excel vba excel-vba

对于VBA,宏和模块,我是新手,所以请包含具体步骤。如何从单个单元格中删除重复的短语,如下所示:

"Brotherhood Of Man - United We Stand Brotherhood Of Man - United We Stand"

我想留下来:

"Brotherhood Of Man - United We Stand"

1 个答案:

答案 0 :(得分:1)

您可以使用带有反向引用的正则表达式来匹配重复的单词或短语。模式^(.+)\s*\1$将匹配任何重复短语,其中包含可选的空格。

Const strText = "Brotherhood Of Man - United We Stand Brotherhood Of Man - United We Stand"

Dim re
Set re = CreateObject("VBScript.RegExp")
re.Pattern = "^(.+)\s*\1$" 

If re.Test(strText) Then
    Debug.Print re.Replace(strText, "$1")
End If

输出:

Brotherhood Of Man - United We Stand

修改,关于评论:

要检查A列中的每个单元格,请在工作表中添加一个子例程,该子例程迭代每个单元格并将单元格值发送到正则表达式解析器。例如,要为范围A1:A100

运行它
Sub UpdateCells()

    ' Create our regex. This will never change, so do it up front.
    Dim re
    Set re = CreateObject("VBScript.RegExp")
    re.Pattern = "^(.+)\s*\1$" 

    ' Check every cell in a particular range.
    Dim r As Range
    For Each r In Range("A1:A100")
        If re.Test(r) Then
            r = re.Replace(r, "$1")
        End If
    Next

End Sub