将数字串分成单独的单元格,包括括号/括号内的数字
我有一个列,每个单元格都有一串数字,括号/括号/大括号中的?, – 和数字。 一个很好的例子就像下面这样:
3????0{1012}?121-2[101]--01221111(01)1
如何将string分隔成不同的单元格,在这种情况下,“字符”是指圆括号/括号/大括号(包括括号/括号/大括号)内的任何数字,?, – 和值?
实际上,上面的string会变成下面的(间隔开来表示一个单独的单元格):
3 ? ? ? ? 0 {1012} ? 1 2 1 - 2 [101] - - 0 1 2 2 1 1 1 1 (01) 1
圆括号/括号/大括号内的数字数量有所不同。 任何string中都没有字母。
假设数据在列A中,从第1行开始,并且希望结果在列B中开始,并且为列A中的每一行数据进行右移,以下是仅使用工作表公式的备用方法。
在B1单元格中使用这个公式:
=IF(OR(LEFT(A1,1)={"(","[","{"}),LEFT(A1,MIN(FIND({")","]","}"},A1&")]}"))),IFERROR(--LEFT(A1,1),LEFT(A1,1)))
在单元格C1中使用这个公式:
=IF(OR(MID($A1,SUMPRODUCT(LEN($B1:B1))+1,1)={"(","[","{"}),MID($A1,SUMPRODUCT(LEN($B1:B1))+1,MIN(FIND({")","]","}"},$A1&")]}",SUMPRODUCT(LEN($B1:B1))+1))-SUMPRODUCT(LEN($B1:B1))),IFERROR(--MID($A1,SUMPRODUCT(LEN($B1:B1))+1,1),MID($A1,SUMPRODUCT(LEN($B1:B1))+1,1)))
复制C1公式,直到它开始给你空白(没有更多的项目从A字段中的string中分离出来)。 在你的例子中,需要将它复制到列AA。 然后,您可以将公式向下复制到列A数据的其余部分。
这个给你!
RegEx方法:
Sub Test_RegEx() Dim s, col, m s = "3????0{1012}?121-2[101]--01221111(01)1" Set col = CreateObject("Scripting.Dictionary") With CreateObject("VBScript.RegExp") .Global = True .Pattern = "(?:\d|-|\?|\(\d+\)|\[\d+\]|\{\d+\})" For Each m In .Execute(s) col(col.Count) = m Next End With MsgBox Join(col.items) ' 3 ? ? ? ? 0 {1012} ? 1 2 1 - 2 [101] - - 0 1 2 2 1 1 1 1 (01) 1 End Sub
循环方法:
Sub Test_Loop() Dim s, col, q, t, k, i s = "3????0{1012}?121-2[101]--01221111(01)1" Set col = CreateObject("Scripting.Dictionary") q = "_" t = True k = 0 For i = 1 To Len(s) t = (t Or InStr(1, ")]}", q) > 0) And InStr(1, "([{", q) = 0 q = Mid(s, i, 1) If t Then k = k + 1 col(k) = col(k) & q Next MsgBox Join(col.items) ' 3 ? ? ? ? 0 {1012} ? 1 2 1 - 2 [101] - - 0 1 2 2 1 1 1 1 (01) 1 End Sub
别的东西看:)
Sub test() 'String to parse through Dim aStr As String 'final string to print Dim finalString As String aStr = "3????0{1012}?121-2[101]--01221111(01)1" 'Loop through string For i = 1 To Len(aStr) 'The character to look at char = Mid(aStr, i, 1) 'Check if the character is an opening brace, curly brace, or parenthesis Dim result As String Select Case char Case "[" result = loop_until_end(Mid(aStr, i + 1), "]") i = i + Len(result) result = char & result Case "(" result = loop_until_end(Mid(aStr, i + 1), ")") i = i + Len(result) result = char & result Case "{" result = loop_until_end(Mid(aStr, i + 1), "}") i = i + Len(result) result = char & result Case Else result = Mid(aStr, i, 1) End Select finalString = finalString & result & " " Next Debug.Print (finalString) End Sub 'Loops through and concatenate to a final string until the end_char is found 'Returns a substring starting from the character after Function loop_until_end(aStr, end_char) idx = 1 If (Len(aStr) <= 1) Then loop_until_end = aStr Else char = Mid(aStr, idx, 1) Do Until (char = end_char) idx = idx + 1 char = Mid(aStr, idx, 1) Loop End If loop_until_end = Mid(aStr, 1, idx) End Function