拆分具有不一致分隔符的字符串

时间:2011-02-22 03:33:44

标签: excel vba excel-vba split

我有一个包含城市,州和邮政编码的专栏。

CITY_STATE_ZIP                                           
--------------------------------------------------
Monroe, IN 46711
South Bend, IN 46615
Alexandria, IN 46001

我希望将三个单词“CITY_STATE_ZIP”拆分为不同的列。

      CITY STATE      ZIP
---------- ---------- --------------------
    Monroe IN         46711
South Bend IN         46615
Alexandria IN         46001

4 个答案:

答案 0 :(得分:2)

如果您想使用VBA,可以按照以下步骤操作。

Sub splitIntoCols()

    Dim oRange As Excel.Range
    Dim oCell As Excel.Range
    Dim vValue As Variant
    Dim sCity As String
    Dim sState As String
    Dim sZipCode As String

    Set oRange = ActiveWorkbook.Sheets(1).Range("A3:A100")

    For Each oCell In oRange

        'Takes the whole value
        vValue = oCell.Value

        'Retrieve the City name (with or without spaces)
        sCity = Left(vValue, InStr(vValue, ",") - 1)

        'Remove the city name from the array
        vValue = Trim(Mid(vValue, InStr(vValue, ",") + 1))

        'Split the value by spaces
        vValue = split(vValue, " ")

        sState = vValue(0)
        sZipCode = vValue(1)

    Next

End Sub

答案 1 :(得分:0)

有一个菜单项“Text to Columns”,它启动了一个向导来执行此操作。 (如果您需要VBA代码,可以打开宏录制器并查看它生成的内容。)

答案 2 :(得分:0)

假设您的单元格位于A列:

Sub a()
Dim r As Range
Set r = Range(Range("A1"), Range("A1").End(xlDown))
For Each k In r
   Cells(k.Row, 4) = Mid(k, Len(k) - 5)
   Cells(k.Row, 3) = Mid(k, Len(k) - 7, 2)
   Cells(k.Row, 2) = Mid(k, 1, Len(k) - 10)
Next k
End Sub

答案 3 :(得分:0)

如果你想在宏观或电子表格中尝试这样做,我很不确定。以下内容适用于电子表格,可以针对宏进行修改。

假设列D中的数据列,此示例在D4中拆分字符串。

字段D5具有

功能
=LEFT(D4, FIND(",",D4)-1)

字段D6具有

功能
=LEFT(MID(D4,FIND(",",D4)+2,LEN(D4)),FIND(" ", MID(D4,FIND(",",D4)+2,LEN(D4))))

Field D7

=RIGHT(MID(D4,FIND(",",D4)+2,LEN(D4)),LEN(MID(D4,FIND(",",D4)+2,LEN(D4))) -FIND(" ", MID(D4,FIND(",",D4)+2,LEN(D4))))