获取括号之间的值,一个string中的多个匹配

我的电子表格有一个像这样的string值的列:

some text (text1) some test (text2) (text1) 

如何获得括号之间的所有值? 我正在寻找的结果是:

 text1, text2 

即使text1, text2... testn出现在单元格中,我只需要在结果中只有一次。

我在这里find了函数GetParen : 获取括号内的值

这是有帮助的,但它在圆括号中给了拳头可用的价值,而忽略了其余的部分。

对于单个条目具有一个用户定义的function并且对于所有条目的集合结果具有另一个用户定义的function似乎是不切实际的。

将以下内容粘贴到标准模块代码表中。

 Function getBracketedText(str As String, _ Optional pos As Integer = 0, _ Optional delim As String = ", ", _ Optional dupes As Boolean = False) Dim tmp As String, txt As String, a As Long, b As Long, p As Long, arr() As Variant tmp = str ReDim arr(1 To 1) For b = 1 To (Len(tmp) - Len(Replace(tmp, Chr(40), vbNullString))) p = InStr(p + 1, tmp, Chr(40)) txt = Trim(Mid(tmp, p + 1, InStr(p + 1, tmp, Chr(41)) - (p + 1))) If UBound(Filter(arr, txt, True)) < 0 Or dupes Then '<~~ check for duplicates within the array a = a + 1 ReDim Preserve arr(1 To a) arr(UBound(arr)) = txt End If Next b If CBool(pos) Then getBracketedText = arr(pos) Else getBracketedText = Join(arr, delim) End If End Function 

像其他任何本地工作表函数一样使用。 有可选的参数来检索一个单独的元素或集合,以及更改默认的<comma> <space>分隔符。

bracket_text_no_duplicates

这段代码适用于我:

 Sub takingTheText() Dim iniP 'first parenthesis Dim endP 'last parentehis Dim myText 'the text Dim txtLen Dim i Dim tmp Dim j myText = Range("A1").Value txtLen = Len(myText) j = 0 Do 'Loop in the text i = i + 1 'a counter iniP = InStr(1, myText, "(", 1) 'found the first occurence of the ( endP = InStr(1, myText, ")", 1) 'same as above tmp = tmp & Right(Left(myText, i), 1) 'take the text garbage text If i = iniP Then 'here comes the work j = j + 1 'here take the cell index myText = Replace(myText, tmp, "") 'remove the garbage text in front the first ( tmp = Left(myText, endP - iniP - 1) 'reuse the var to store the usefull text Cells(1, 2).Value = Cells(1, 2).Value & Chr(10) & tmp 'store in the cell B1 'If you want to stored in separated cells use the below code 'Cells(j, 2).Value = tmp myText = Replace(myText, tmp & ")", "", 1, 1) ' remove the garbage text from the main text tmp = Empty 'empty the var i = 0 'reset the main counter End If Loop While endP <> 0 

结束小组

结果:

在这里输入图像说明

请检查并告诉我是否可以。

编辑#1

Cells(1, 2).Value = Cells(1, 2).Value & Chr(10) & tmp此代码将文本以单独的行存储在同一单元格内,可能是因为chr(10) (也可以使用chr(13) ),那么你可以使用Cells(1, 2).Value = Cells(1, 2).Value & " " & tmp ,或者使用任何其他字符来代替string里面的&符号