以下代码可使用多个正则表达式对目标单元格进行多次匹配尝试,如匹配成功,将停止尝试匹配其他正则表达式,并且使用该正则表达式相对应的替换表达式进行替换,返回替换结果。
使用前需要做Early Binding。即在VBE编辑器中,选择菜单栏中的Tool — Reference,如图:
弹出如下图的对话框后,选择Microsoft VBSscript Regular Expression 5.5,打钩,点OK。
此UDF的使用方法为:
Text参数:需要进行处理的原始文字或单元格。
MatchPatternRange参数:正则表达式组所在的单元格范围。请将多个正则表达式存放在表格中的一行或一列内,作为MatchPatternRange参数传入。
ReplacePattern参数:每个正则表达式相对应的替换字串符所在的单元格范围。请将用来作替换的文字放在正则表达式隔壁的行或列内,作为ReplacePatternRange参数传入。
IgnoreCase参数:在查找时是否忽略大小写,默认值为True,即忽略大小写区别。
Function RangeRegexReplace(ByVal Text As String, ByVal MatchPatternRange As Range, ByVal ReplacePatternRange As Range, Optional ByVal IngoreCase As Boolean = True) As String ‘By Jing He 2017-9-1 Dim i As Integer, j As Integer, x As Integer Dim pattern() As String, replace() As String ReDim pattern(0 To MatchPatternRange.count - 1) As String ReDim replace(0 To ReplacePatternRange.count - 1) As String i = 0 For Each c In MatchPatternRange pattern(i) = c.Value i = i + 1 Next c j = 0 For Each c In ReplacePatternRange replace(j) = c.Value j = j + 1 Next c If i <> j Then RangeRegexReplace = "Numbers of cells in MatchPatternRange and ReplacePatternRange are not equal." End If Dim regex As New RegExp With regex .Global = True .MultiLine = True .IgnoreCase = IngoreCase End With RangeRegexReplace = "-" For x = 0 To i - 1 Step 1 regex.pattern = pattern(x) If regex.Test(Text) Then RangeRegexReplace = regex.replace(Text, replace(x)) End If Next x End Function
顺便附带一个使用单个正则表达式进行查找替换的自定义函数,使用这个函数时,正则表达式可以直接写入公式的参数内,不需要放在单元格内再去引用。
Function RegexReplace(ByVal Text As String, ByVal MatchPattern As String, ByVal ReplacePattern As String, Optional ByVal IngoreCase As Boolean = True) As String ‘By Jing He 2017-9-1 Dim regex As New RegExp With regex .Global = True .MultiLine = True .IgnoreCase = IngoreCase .pattern = MatchPattern End With If regex.Test(Text) Then RegexReplace = regex.replace(Text, ReplacePattern) Else RegexReplace = "-" End If End Function
时间: 2024-10-12 22:06:08