Here's some code I wrote some time ago to split a cell containing something
like
New York, New York 10021
into 3 cells. It uses the Split function that was introduced in XL2000, so you
need that version or higher. It handles states that are written out, e.g.
Illinois, and state names that are two words (New York, South Carolina, West
Virginia, etc), as above, or the two letter abbreviations like NY, SC, WV.
To use the function, you need to go to the VB Editor (ALT+F11), select your
workbook over in the project pane on the upper left, insert a module into your
project (VBE's Insert menu), then paste the code below (all lines *between*
the lines of tildes) into the new code pane you see on the right.
On the worksheet, let's say your City-State-Zip is in cell D2. Select 3 cells,
E2:G2, enter the formula
=CityStateZip(D2)
and press CTRL+SHIFT+ENTER to enter it as an array formula. The city will be
placed in E2, state in F2, and Zip in G2.
Copy the formula down, then to convert to values, select the three columns,
Edit/Copy them, then Edit/Paste Special and select the Values option.
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Option Explicit
Option Compare Text
Function CityStateZip(sAddress As String) As Variant
Dim sTemp As String
Dim Words() As String
Dim N As Long
Dim City As String
Dim State As String
Dim Zip As String
Dim TwoWords As Boolean
'remove leading and trailing spaces and reduce
'runs of embedded spaces to a single space
sText = Application.Trim(sText)
'split the into individual words at the spaces
Words = Split(sTemp, " ")
N = UBound(Words)
If N < 2 Then
'require that there are at least 3 words
'representing city, state, and zip code
Zip = "???"
State = "???"
City = sTemp
Else
Zip = Words(N)
State = Words(N - 1)
ReDim Preserve Words(0 To N - 2)
TwoWords = False
If Len(State) > 2 And N >= 3 Then
'state is written out
sTemp = UCase$(State)
Select Case UCase$(Words(N - 2))
Case "NEW"
Select Case sTemp
Case "YORK", "JERSEY", "HAMPSHIRE", "MEXICO"
TwoWords = True
End Select
Case "NORTH", "SOUTH"
Select Case sTemp
Case "CAROLINA", "DAKOTA"
TwoWords = True
End Select
Case "WEST"
TwoWords = (sTemp = "VIRGINIA")
Case "RHODE"
TwoWords = (sTemp = "ISLAND")
End Select
If TwoWords Then
State = Words(N - 2) & " " & State
ReDim Preserve Words(0 To N - 3)
End If
End If
'concatenate what's left in the array as the city
City = Join(Words, " ")
If Right$(City, 1) = "," Then City = Left$(City, Len(City) - 1)
End If 'at least 3 words
CityStateZip = Array(City, State, Zip)
End Function 'CityStateZip
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~