如何根据特殊字符分割字符串(多次)

时间:2018-09-04 08:22:15

标签: excel vba string

我正在尝试根据&符分割字符串,删除所有&符并将每个部分分成列。

每次的字符串数都不同。

示例文字:

enter image description here

我的输出:

enter image description here

我需要什么:

enter image description here

18:13:16Z

2 个答案:

答案 0 :(得分:1)

您可以尝试类似的事情

Sub SplitAmper()

Const AP = "&"
Dim v As Variant
Dim rg As Range

    Set rg = Range("A2:A7") ' Adjust to your needs

    Dim sngCell As Range
    For Each sngCell In rg
        v = Split(sngCell.Value, AP)
        Cells(sngCell.Row, 1).Resize(, UBound(v) + 1) = v
    Next

End Sub

更新:SJR评论中提到的另一种解决方案是文本到列

Sub AnotherAmper()

Const AP = "&"
Dim rg As Range

Set rg = Range("A1:A7")    ' Adjust to your needs


    rg.TextToColumns Destination:=Range("B1"), DataType:=xlDelimited, _
                     Other:=True, OtherChar:=AP

End Sub

答案 1 :(得分:1)

另一种选择(@Storax的方法除外)是使用正则表达式,这可能会导致更多的&符号。

Option Explicit
Public Sub FindNames()
    Dim rng As Range
    Dim j As Long
    Dim c, Match

    ' Update for your range
    With ActiveSheet
        Set rng = .Range(.Cells(1, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
    End With

    With CreateObject("vbscript.regexp")
        .Global = True
        .Pattern = "\w+"

        For Each c In rng
            j = 0
            If .test(c.Value2) Then
                For Each Match In .Execute(c.Value2)
                    j = j + 1
                    c.Offset(0, j).Value2 = Match
                Next Match
            End If
        Next c
    End With
End Sub