我在单元格A1中有以下数据 -
EP10101010 | EP202020 | EP300005 | US789456 | US876543 | NZ90876 | LP98789 | LP88888
我希望将以相同字符(例如EP)开头的值分隔并分组到一个单元格中。
期望的输出:
Cell A2 - EP10101010 | EP202020 | EP300005
Cell A3 - US789456 | US876543
Cell A4 - NZ90876
Cell A5 - LP98789 | LP88888
答案 0 :(得分:0)
Sub main()
Dim strng As Variant, strngs As Variant
Dim lastStrngID As String, resStrng As String
Dim rowIndex As Long
strngs = Split(Replace(Range("A1"), " ", ""), "|")
rowIndex = 2
lastStrngID = Left(strngs(0), 2)
For Each strng In strngs
If Left(strng, 2) <> lastStrngID Then
Cells(rowIndex, 1).Value = Left(resStrng, Len(resStrng) - 1)
rowIndex = rowIndex + 1
lastStrngID = Left(strng, 2)
resStrng = strng & " | "
Else
resStrng = resStrng & strng & "|"
End If
Next
Cells(rowIndex, 1).Value = Left(resStrng, Len(resStrng) - 1)
End Sub
或者,或者:
Sub main2()
Dim strng As Variant
With CreateObject("Scripting.Dictionary")
For Each strng In Split(Replace(Range("A1"), " ", ""), "|")
.Item(Left(strng, 2)) = .Item(Left(strng, 2)) & "|" & strng & "|"
Next
Range("A2").Resize(.count).Value = Application.Transpose(.Items)
With Range("A2").Resize(.count)
.Replace "||", "--"
.Replace "|", ""
.Replace "--", " | "
End With
End With
End Sub
答案 1 :(得分:0)
我有这段代码:
Public Function SplitStart(start As String, text As String) As String
Dim splitString() As String
Dim st As Variant
Dim returnstring As String
Dim i As Integer
Dim trimmed As String
splitString = Split(text, " | ")
returnstring = ""
For Each st In splitString
trimmed = Trim(st)
If Left(trimmed, Len(start)) = start Then
If returnstring <> "" Then
returnstring = returnstring + " | "
End If
returnstring = returnstring + trimmed
End If
Next
SplitStart = returnstring
End Function
您将其插入模块,然后您可以使用
=splitstart("EP";A1)
例如在A2
中