我需要在VBA excel中进行复杂的拆分。我有一列包含字符串的单元格,如下例所示:
Name1 (10%), Name2 (50%), Name3, Name4 (40%)
我需要拆分此字符串并将每个值返回到工作表上不相邻的特定单元格。例如:
Name1 - Cell B1
10% - Cell C1
Name2 - Cell M1
50% - Cell N1
Name3 - Cell X1
(blank)- Cell Y1
Name4 - Cell AD1
40% - Cell AE1
我提出解决方案的主要问题是字符串可以是任意长度。
它们可能包含:
1-10个名字,
每个名称可能或可能不会有一个百分比
我还在做研究和测试,但我找不到真正可行的解决方案。任何想法将不胜感激
答案 0 :(得分:1)
这是单程
Sub SplitNames()
Dim vaNames As Variant
Dim vaPct As Variant
Dim i As Long
'split on comma
vaNames = Split("Name1 (10%), Name2(50%), Name3, Name4(40%)", ",")
'loop through the name/pct pairs
For i = LBound(vaNames) To UBound(vaNames)
'split each on open paren
vaPct = Split(vaNames(i), "(")
'Write the name to a cell
Sheet1.Range("A1").Offset(0, (11 * i) + 2).Value = vaPct(0)
'If there's a pct, write it to a cell
If UBound(vaPct) >= 1 Then
Sheet1.Range("A1").Offset(0, (11 * i) + 3).Value = Replace(vaPct(1), ")", vbNullString)
End If
Next i
End Sub
答案 1 :(得分:0)
查找space
替换为,
查找(
替换为nothing
查找),
替换为nothing
查找)
替换为nothing
以,
分隔的列的文本(将连续分隔符视为未选中的分隔符)
插入适合的列。
查找/替换的替代方法:
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1," ",","),"(",""),"),",""),")","")
向下复制以适应,选择列,复制,选择性粘贴,然后选择文本到列。
答案 2 :(得分:0)
Sub SplitRoast()
Dim x() As String
x = Split(Replace(Replace(Replace _
(Replace(Range("A1").Value, ")", ""), "(", ""), ", ", ","), " ", ","), ",")
Range("B1").Value = x(0)
Range("C1").Value = x(1)
Range("M1").Value = x(2)
Range("N1").Value = x(3)
Range("X1").Value = x(4)
'(blank)- Cell Y1
Range("AD1").Value = x(5)
Range("AE1").Value = x(6)
End Sub