代码之家  ›  专栏  ›  技术社区  ›  Elodia

提取多个表达式

  •  0
  • Elodia  · 技术社区  · 7 年前

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

    ,FC757_random_name,AP372_another_one,FC782_again_different,FC082_samesamebutdifferent,

    我只需要提取表达式开头的字母数字值,所以 , _

    我用下面的表达式实现了一个表达式,但我需要所有表达式。

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

    我还修改了文本到数据的转换,但无法同时处理多行。 理想情况下,这只适用于公式,但我想(/害怕)我需要VBA或宏,这是我以前从未使用过的。

    感谢您的帮助!

    3 回复  |  直到 7 年前
        1
  •  0
  •   user4039065 user4039065    7 年前

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

    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
    

    enter image description here

        2
  •  0
  •   Kevin    7 年前

    我想你在找像这样的媒体 Alt + F11 然后选择 插入(>);单元 然后粘贴以下代码:

    Public Function GetUsers(UserNameProject As String)
    
    Dim userArray() As String
    Dim users As String
    Dim intPos As Integer
    
    'this will split the users into an array based on the commas
    userArray = Split(UserNameProject, ",")
    
    'loop through the array and process any non blank element and extract user
    'based on the position of the first underscore
    For i = LBound(userArray) To UBound(userArray)
          If Len(Trim(userArray(i))) > 0 Then
            intPos = InStr(1, userArray(i), "_")
            users = users & "," & Left(userArray(i), intPos - 1)
          End If
    Next
    
    GetUsers = users
    
    End Function
    

    如果您的字符串位于A1中,则通过以下方式使用 =GetUsers(A1) 在相应的单元格中。我想这应该让你开始!

        3
  •  0
  •   tigeravatar    7 年前

    要清除多余逗号的数据,请在单元格B1中使用以下公式:

    =TRIM(SUBSTITUTE(SUBSTITUTE(TRIM(SUBSTITUTE(SUBSTITUTE(A1;" ";"||");";";" "));" ";";");"||";" "))
    

    然后在单元格C1中使用此公式,反复复制以从每个部分中提取所需的零件:

    =IFERROR(INDEX(TRIM(LEFT(SUBSTITUTE(TRIM(MID(SUBSTITUTE($B1;";";REPT(" ";LEN($B1)));LEN($B1)*(ROW($A$1:INDEX($A:$A;LEN($B1)-LEN(SUBSTITUTE($B1;";";""))+1))-1)+1;LEN($B1)));"_";REPT(" ";LEN($B1)));LEN($B1)));COLUMN(A1));"")