如何在Excel中将一列拆分为三列?

时间:2017-10-10 11:19:45

标签: excel

如何将第一张图片(整个地址)分成第二张图片(地址,城市,州,邮政编码)。我有超过一千个数据,所以请建议我简单的方法?

所有整个地址的格式为 729 quail creek drive,frisco tx 75034

我需要将地址分为 729 quail creek drive ,City为 frisco ,状态为 tx ,邮政编码为 75034 < /强>

Whole Address

Split Address, city, state, zipcode 感谢

2 个答案:

答案 0 :(得分:1)

如果您知道您的数据将始终采用以下格式:

<address>, <city> <2-letter state> <5-digit zip code>

然后这是我能想到的最简单的方法:

<address>的公式:

= LEFT(A1,FIND(",",A1)-1)

<city>的公式:

= MID(A1,FIND(",",A1)+2,LEN(A1)-FIND(",",A1)-10)

<2-letter state>的公式:

= MID(A1,LEN(A1)-7,2)

<5-digit zip code>的公式:

= RIGHT(A1,5)

见下面的例子。

enter image description here

答案 1 :(得分:1)

这可以通过RegExp来完成,但不是找出RegExp模式,而是使用了Split函数和几个数组。我假设地址在逗号之前。

Sub SplitAddress()
    Dim Addresses As Variant, results As Variant, tmp As Variant
    Dim i As Long, j As Long

    ' Update for you range
    With Sheet1
        'Trick to get 1D array from range
        Addresses = Application.Transpose(.Range(.Cells(2, "A"), .Cells(.Cells(.Rows.Count, "A").End(xlUp).Row, "A")))
    End With

    ReDim results(1 To UBound(Addresses), 1 To 4)

    For i = 1 To UBound(results, 1)
        tmp = Split(Addresses(i), ",")
        results(i, 1) = Trim(tmp(0))

        tmp = Split(Trim(tmp(1)), " ")

        For j = LBound(tmp) To UBound(tmp)
            results(i, j + 2) = Trim(tmp(j))
        Next j
    Next i

    ' Update for your destination
    With Sheet1.Cells(2, "B")
        Range(.Offset(0, 0), .Offset(UBound(results, 1) - 1, UBound(results, 2) - 1)).Value2 = results
    End With
End Sub

使用RegExp

更新

此方法使用RegExp分割字符串

Sub splitAddressRegEx()
    Dim ReGex As Object
    Dim Addresses As Range
    Dim j As Long
    Dim c, m

    ' Update for your range
    With Sheet1
        Set Addresses = .Range(.Cells(2, "A"), .Cells(.Cells(.Rows.Count, "A").End(xlUp).Row, "A"))
    End With
    Set ReGex = CreateObject("VBScript.RegExp")

    With ReGex
        .Global = True
        .IgnoreCase = True
        .Pattern = "(.+?(?=,))|(\w+)"
    End With

    For Each c In Addresses
        j = 1
        If ReGex.Test(c.Value2) Then
            For Each m In ReGex.Execute(c.Value2)
                ' Update for your output
                c.Offset(0, j).Value2 = m
                j = j + 1
            Next m
        End If
    Next c

End Sub