Search code examples
vbaexcelexcel-2007

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"


Solution

  • I assume you want a VBA solution since you tagged your question .

    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)