我的电子表格有一个列,其值类似于此字符串:
some text (text1) some test (text2) (text1)
如何获取括号之间的所有值?我要找的结果是:
text1, text2
即使单元格中多次出现text1, text2... testn
,我只需要在结果中使用一次。
我在这里找到了一个函数GetParen
:Get the value between the brackets
这很有帮助,但它在括号中给出了第一个可用的值而忽略了其余的值。
答案 0 :(得分:2)
为个别条目设置一个用户定义函数,而为所有条目的集体结果设置另一个用户定义函数似乎不实用。
将以下内容粘贴到标准模块代码表中。
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
像任何其他本机工作表函数一样使用。有可选参数可以检索单个元素或集合,以及更改默认的&lt; comma&gt;&lt; space&gt; 分隔符。
答案 1 :(得分:1)
此代码适用于我:
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
End Sub
结果:
请检查并告知是否可以。
编辑#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
,或使用任何其他字符代替&
符号中的字符串