首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >VBA:正则表达式(7) -数据整理

VBA:正则表达式(7) -数据整理

作者头像
Exploring
发布2023-10-04 15:08:21
发布2023-10-04 15:08:21
52100
代码可运行
举报
运行总次数:0
代码可运行

需求:数据保存在A列中,数据组之间使用全角逗号(,)分隔,整理之后需要将每组数据开始的圆括号部分移到末尾,并合并相同的全角方括号部分(【】)的内容。实际效果见B列。

示例代码如下:

代码语言:javascript
代码运行次数:0
运行
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-09-30 11:06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 数据处理与编程实践 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档