Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete all characters after the first space in a cell?

I have a list of city names followed by the state in which they are located all in one column in Excel. How can I delete everything after the first space so that the city name is the only thing that's left in the cell?

example: A1 = "johnson TX"
should be just A1= "johnson"

like image 501
dzilla Avatar asked Dec 02 '22 02:12

dzilla


1 Answers

I assume you want a VBA solution since you tagged your question excel-vba.

This works:

Sub KeepCity()
    Dim strCityAndState As String
    Dim strCityOnly As String
    strCityAndState = Range("A1").Value
    strCityOnly = Left(strCityAndState, InStr(strCityAndState, " ") - 1)
    Range("A2").Value = strCityOnly
End Sub

If you don't want VBA and want a cell formula instead, then @JToland's answer works fine, though this one is more concise and doesn't keep the trailing space character:

=LEFT(A1, FIND(" ",A1)-1)
like image 125
Jean-François Corbett Avatar answered Dec 05 '22 15:12

Jean-François Corbett