需求:数据保存在A列中,数据组之间使用全角逗号(,)分隔,整理之后需要将每组数据开始的圆括号部分移到末尾,并合并相同的全角方括号部分(【】)的内容。实际效果见B列。
示例代码如下:
Option Explicit
Option Base 1
Sub RegExpReOrg()
'数据整理
Dim objRegEx As Object, objMatch As Object, objMH As Object
Dim c As Range, rngData As Range
Dim strTxt As String, strKey As String
Dim dic As Object, k As Variant
Set objRegEx = CreateObject("vbscript.regexp")
objRegEx.Pattern = "(\(\d+\))(【.+?】)(.*?),"
objRegEx.Global = True
Set dic = CreateObject("scripting.dictionary")
' 1 清空B列旧数据
Set rngData = Range([A2], Cells(Rows.Count, "A").End(xlUp))
rngData.Offset(0, 1).ClearContents
' 2 遍历各个单元格
For Each c In rngData
strTxt = Application.Clean(c.Value) & "," '在末尾添加一个全角逗号,便于正则匹配
Set objMatch = objRegEx.Execute(strTxt)
If objMatch.Count > 0 Then
dic.RemoveAll '清空字典
For Each objMH In objMatch
strKey = objMH.submatches(1) '键值
If dic.exists(strKey) Then
dic(strKey) = dic(strKey) & "," & objMH.submatches(2) & objMH.submatches(0)
Else
dic(strKey) = objMH.submatches(2) & objMH.submatches(0)
End If
Next
strTxt = ""
For Each k In dic.Keys
strTxt = strTxt & Chr(10) & k & dic(k) '换行显示
Next
c.Offset(0, 1) = Mid(strTxt, 2) '第一个字符是换行符,所以从第2个字符开始取值
End If
Next
Set objMH = Nothing
Set objMatch = Nothing
Set objRegEx = Nothing
MsgBox "Done!"
End Sub
(1)dic.RemoveAll
RemoveAll
方法从 Dictionary 对象中删除所有键项对。
(2)Chr(10) 将返回换行符
(3)Application.Clean
删除文本中所有的非打印字符。
参考资料:
[1] VBA之正则表达式(7)-- 乾坤大挪移(数据整理)(https://blog.csdn.net/taller_2000/article/details/89506634)
[2] RemoveAll 方法(https://learn.microsoft.com/zh-cn/office/vba/language/reference/user-interface-help/removeall-method)
[3] Chr 函数 (Visual Basic for Applications)(https://learn.microsoft.com/zh-cn/office/vba/language/reference/user-interface-help/chr-function)
[4] WorksheetFunction.Clean 方法 (Excel)(https://learn.microsoft.com/zh-cn/office/vba/api/excel.worksheetfunction.clean)