简体   繁体   中英

How to split a string of text in excel based on a given word?

I have a list of combinations of companies, cities, and states in excel, each a string. I would like to split the string of words based on a given word (the city name) and the result to be two columns, one with with company name, one with the city and state.

Splitting on space or symbol delimiters doesn't work because the companies don't all have one word names, and similar for cities.

I have thousands of records and would like to loop this as well. I've tried the SPLIT() function in VBA but not sure how to loop it.

Initial                     Splitting word  Result 1     Result 2
Clean Choc Detroit MI       Detroit         Clean Choc  Detroit MI
Space Kites Des Moines IA   Des Moines      Space Kites Des Moines IA
Tattoosie Chicago IL        Chicago         Tattoosie   Chicago IL
One for Two New York City NYNew York City   One for Two New York City NY
Limonistas Carlsbad CA      Carlsbad        Limonistas  Carlsbad CA

If you want to avoid VBA, the following formulas could work for you:

=LEFT(A2,FIND(B2,A2)-2)

=RIGHT(A2,LEN(A2)-FIND(B2,A2)+1)

You can use this as two functions (one returns the left part, other returns the right part):

Function split1(str As String, dlmtr As String) As String
Dim pt1() As String
pt1 = Split(str, dlmtr)
split1 = pt1(0)
End Function

Function split2(str As String, dlmtr As String) As String
Dim pt2() As String
pt2 = Split(str, dlmtr)
split2 = dlmtr & " " & pt2(1)
End Function

Note that the Delimiter expected is case sensitive

在此处输入图片说明

Or as a Subroutine (tweak as necessary):

Sub split_strings()
Dim rng As Range
Dim dmltr As String: dmltr = "Detroit"

Set rng = Range("A1")

Dim splt() As String
splt = Split(rng.Value, dmltr)
rng.Offset(0, 1).Value = splt(0)
rng.Offset(0, 2).Value = dmltr & " " & splt(1)
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM