其他分享
首页 > 其他分享> > Excel VBA 自定义公式 使用正则表达式提取子字符串

Excel VBA 自定义公式 使用正则表达式提取子字符串

作者:互联网

首先打开Excel自带的VBA开发环境

导入一个库

选择 工具 > 引用

导入下面选中的库,第一次导入需要使劲往下翻,界面特别蛋疼

 

 

然后粘贴下面的代码

Public Function REGEXSUBSTRING(str As String, pat As String, ignoreCase As Boolean, def As String) As String

'Define the regular expression object

Dim RegEx As New RegExp

'Set up regular expression properties

With RegEx

.Global = False 'All occurences are not necessary since a single occurence is enough

.ignoreCase = ignoreCase  'No case-sensitivty

.MultiLine = True 'Check all lines

.Pattern = pat 'pattern

End With


Dim Ms

Set Ms = RegEx.Execute(str)

If Ms.Count <> 0 Then
    REGEXSUBSTRING = Ms.Item(0).Value
Else
    REGEXSUBSTRING = def
End If

End Function

第一个参数是一个待匹配的字符串,也可以是一个单元格,第二个参数是正则表达式,第三个参数是是否忽略大小写,第四个参数是假如没有匹配项返回的默认字符串

我这边测试保存在个人宏工作簿中无法在其他表格中引用或者说找到自定义公式,其实可以另存为成加载宏,然后在别的表格中加载这个表格,这样公式栏中就会自动补全公式了

例如

 

 

 

 

使用示例

 

 

标签:RegEx,VBA,End,String,自定义,REGEXSUBSTRING,Excel,ignoreCase,Ms
来源: https://www.cnblogs.com/leikaifeng/p/15482089.html