Excel 2013 – 如何从单个单元格中删除重复的短语
当谈到VBA,macros和模块时,我是一个新手,所以请包括特定的步骤。 如何删除单个单元格中的重复短语,如下所示:
"Brotherhood Of Man - United We Stand Brotherhood Of Man - United We Stand"
我想留下:
"Brotherhood Of Man - United We Stand"
您可以使用反向引用的正则expression式来匹配重复的单词或短语。 模式^(.+)\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中的每个单元格,请在工作表中添加一个子例程,以迭代每个单元格,并将单元格值发送到正则expression式分析器。 例如,要运行它的范围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