Home » excel » How to add 0 to the beginning of a value in Excel if the value is a certain length

How to add 0 to the beginning of a value in Excel if the value is a certain length

Posted by: admin May 14, 2020 Leave a comment

Questions:

I don’t really have good knowledge of excel function, but I am hoping this is something i can do in an excel spreadsheet instead of writing a text parser to do this and have to put the data back in.

I basically want to do this in excel:

IF cellValueLength = 4 characters OR cellValueLength = 9 characters THEN cellValue = "0" + cellValue

Sorry for the weird pseudo code, but I’m not sure how else to clearly communicate what I am trying to accomplish.

Also the cell values can be strings. In fact I’d prefer if they were all strings since Excel automatically converting them to numbers is what messed this up in the first place.

Any suggestions would be appreciated.

How to&Answers:

As follow up from comments, this one works:

=IF(OR(LEN(A1)=4,LEN(A1)=9),"0","") & A1

Answer:

If you want this done “in place”, then select the cells and run this macro:

Sub PreZero()
    For Each r In Selection
        v = r.Text
        If Len(v) = 4 Then
            r.NumberFormat = "00000"
        End If
        If Len(v) = 9 Then
            r.NumberFormat = "0000000000"
        End If
    Next r
End Sub

Answer:

In the format menu you should be able to format the cells as numbers and make it the way you described.

I hope this helped you!