Results 1 to 3 of 3

Thread: [Excel] How do I remove a leading space

  1. #1
    New Member
    Join Date
    Aug 12
    Posts
    1

    [Excel] How do I remove a leading space

    I have up to 20 6-digit numbers in one cell separated by spaces. Example 609134 60T134 60U134 373103
    I'm extracting these from another in-house database and sometimes the 6 digit number is preceded by a space.
    What I need to do is remove any leading or trailing spaces and ensure that the spaces between the numbers are single spaces.

    After removing the leading space or spaces, I need to then copy just the first number to a cell, then the remaining to anther cell for that, I'm using:
    RowCount = 2
    Do While Range("J" & (RowCount)) <> ""
    Range("K" & RowCount).Select
    ActiveCell.FormulaR1C1 = "=LEFT(RC[2],7)"
    Range("L" & RowCount).Select
    ActiveCell.FormulaR1C1 = "=RIGHT(RC[1],LEN(RC[1])-8)"
    RowCount = RowCount + 1
    Loop

    If the cell containing all the numbers has a leading zero, I end up with the first 5 digits of the number and the cell containing the rest of the numbers starts with the last digit of the first nuimber, like so:
    60913 and 4 60T134 60U134 373103

    Instead of
    619134 and 60T134 60U134 373103

    How do I resolve this?

    Thank you
    Dee

  2. #2
    Fanatic Member
    Join Date
    Oct 08
    Location
    Midwest Region, United States
    Posts
    1,022

    Re: [Excel] How do I remove a leading space

    This code will turn all double spaces (or more) into single spaces:

    Code:
    Sub find_space()
        result = True
        While result = True
        On Error Resume Next
        result = Cells.Find(What:="  ", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
            xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
            , SearchFormat:=False).Activate
            
        If Err.Number = 91 Then Exit Sub    'didn't find double space(s)
            
        If result = True Then
            Cells.Replace What:="  ", Replacement:=" ", LookAt:=xlPart, SearchOrder _
                :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
        End If
        Wend
    End Sub

  3. #3
    Lively Member
    Join Date
    Jan 09
    Posts
    84

    Re: [Excel] How do I remove a leading space

    Take a look the TRIM function which removes leading and trailing spaces.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •