vba自定义函数提取字符串-正则表达式

发布时间 2023-06-30 10:04:55作者: 一个不会玩的狗子
Function ExtractString(inputString As String, pattern As String) As String
    Dim regex As Object
    Dim matches As Object
    Dim match As Object
    
    ' 创建 RegExp 对象
    Set regex = CreateObject("VBScript.RegExp")
    
    With regex
        .Global = True ' 匹配所有出现
        .IgnoreCase = True ' 忽略大小写
        .Pattern = pattern ' 正则表达式模式
    End With
    
    ' 执行匹配操作
    Set matches = regex.Execute(inputString)
    
    ' 检查是否有匹配结果
    If matches.Count > 0 Then
        ' 提取第一个匹配结果
        Set match = matches.Item(0)
        ExtractString = match.Value
    Else
        ' 没有匹配结果
        ExtractString = ""
    End If
    
    ' 清理对象
    Set regex = Nothing
    Set matches = Nothing
    Set match = Nothing
End Function
View Code

该函数,粘贴到Excel的模块中,直接调用即可