新建一个Excel工作表
然后打开Excel自带的VBA开发环境
导入一个库
选择 工具 > 引用
导入下面选中的库,第一次导入需要使劲往下翻,界面特别蛋疼
GIF
然后粘贴下面的代码
Public Function RegexSubString(text As String, pattern As String, Optional matcheIndex As Integer = 0, Optional subMatcheIndex As Integer = -1, Optional ignoreCase As Boolean = False, Optional multiLine As Boolean = True, Optional defaultText As String = "") As String ' text 参数 待匹配的文本 ' pattern 参数 正则表达式或者说模式文本 ' matcheIndex 参数(可选) 第几个匹配项的索引,0是开头第一个,-1是末尾第一个依次类推 ' subMatcheIndex 参数(可选) 匹配项中子匹配项的索引,从0开始,默认值是-1代表返回完整匹配项 ' ignoreCase 参数(可选) 如果为 True,则匹配忽略字母大小写 ' multiLine 参数(可选) 如果为 True,则模式匹配发生在换行符之间 ' defaultText 参数(可选) 假如没有匹配项则返回的默认文本,假如有匹配项但是子匹配项索引错误也会返回此值 Dim RegEx As New RegExp With RegEx .Global = True 'True,则找到字符串中模式的所有匹配项。如果为 False,则仅找到第一个匹配项 .ignoreCase = ignoreCase .multiLine = multiLine .pattern = pattern End With Dim ms As MatchCollection, m As Match, gs As SubMatches Set ms = RegEx.Execute(text) If ms.Count = 0 Then RegexSubString = defaultText Exit Function End If Dim index As Integer If matcheIndex >= 0 Then index = matcheIndex Else index = ms.Count + matcheIndex End If If index >= 0 And index < ms.Count Then Set m = ms.Item(index) Else RegexSubString = defaultText Exit Function End If Set gs = m.SubMatches If subMatcheIndex = -1 Then RegexSubString = m.Value Exit Function ElseIf subMatcheIndex >= 0 And subMatcheIndex < gs.Count Then RegexSubString = gs.Item(subMatcheIndex) Else RegexSubString = defaultText Exit Function End If End Function
GIF
关闭VBA开发环境,但不关闭工作表,然后把这个工作表另存为加载宏,因为excel有些历史记录关不掉,所以GIF录得区域过小,但是应该能看懂
然后关闭该工作表,打开其他工作表,然后才去点击Excel加载项,加载项的名字就是你另存为时输入的名字
简单使用示例
后面附一个使用正则表达式替换文本的VBA脚本
Public Function RegexReplace(text As String, pattern As String, replaceText As String, Optional replaceAll As Boolean = False, Optional ignoreCase As Boolean = False, Optional multiLine As Boolean = True) As String ' text 参数 待匹配的文本 ' pattern 参数 正则表达式或者说模式文本 ' replaceText 参数 用来替换的文本,可以使用 $1 来引用第一个子匹配项,依次类推 ' replaceAll 参数(可选) 是否替换所有匹配项 ' ignoreCase 参数(可选) 如果为 True,则匹配忽略字母大小写 ' multiLine 参数(可选) 如果为 True,则模式匹配发生在换行符之间 Dim RegEx As New RegExp With RegEx .Global = replaceAll 'True,则找到字符串中模式的所有匹配项。如果为 False,则仅找到第一个匹配项 .ignoreCase = ignoreCase .multiLine = multiLine .pattern = pattern End With RegexReplace = RegEx.Replace(text, replaceText) End Function
简单使用示例