首页 > 解决方案 > 提取多个表达式

问题描述

我有一个单元格,其中包含分配给这样的项目的用户名

,FC757_random_name,AP372_another_one,FC782_again_different,FC082_samesamebutdifferent,

我只需要提取表达式开头的字母数字值,因此介于,和之间的所有内容_

我用以下方法使它适用于一个表达式,但我需要所有这些。

= MID(A1;FIND(",";A1)+1;FIND("_";A1)-FIND(",";A1)-1)

我还修改了 Text to Data,但无法使其同时适用于多行。理想情况下,这只适用于公式,但我想(/恐惧)我需要 VBA 或宏,这是我以前从未使用过的。

所有帮助将不胜感激!

标签: excelexcel-formula

解决方案


这是一个基于的用户定义函数。

Option Explicit

Function extractMultipleExpressions(str As String, _
                  Optional delim As String = ", ")
    Dim n As Long, nums() As Variant
    Static rgx As Object, cmat As Object

    'with rgx as static, it only has to be created once; beneficial when filling a long column with this UDF
    If rgx Is Nothing Then
        Set rgx = CreateObject("VBScript.RegExp")
    End If
    extractMultipleExpressions = vbNullString

    With rgx
        .Global = True
        .MultiLine = False
        .Pattern = "[A-Z]{2}[0-9]{3}"
        If .Test(str) Then
            Set cmat = .Execute(str)
            'resize the nums array to accept the matches
            ReDim nums(cmat.Count - 1)
            'populate the nums array with the matches
            For n = LBound(nums) To UBound(nums)
                nums(n) = cmat.Item(n)
            Next n
            'convert the nums array to a delimited string
            extractMultipleExpressions = Join(nums, delim)
        End If
    End With
End Function

在此处输入图像描述


推荐阅读