Cell Must Have Exactly 4 Digits Entered, And 0s Must Show at Beginning

davidjacoby

New Member
Joined
May 6, 2011
Messages
5
Hello! First time poster! I tried searching for this answer but couldn't find anything...

I am trying to set up a template in which a column of cells is last four digits of a person's social security number. I would like for there to be 0s at the beginning, so if the person's last four digits are 0123 then it will show "0123" and not just "123". I have done that by going to Format Cells => Number => Custom and having the Type be "0000"

HOWEVER...

I also want to make sure that the person always enters exactly four digits. So, if the number is 1234 and the person accidentally just enters "123", it will show up as "0123", which is incorrect. How can I set up a rule that exactly four digits must always be entered and some sort of warning or pop up box or something will happen if something other than four digits are entered?

Thank you very much for your help!

David
 

Excel Facts

Links? Where??
If Excel says you have links but you can't find them, go to Formulas, Name Manager. Look for old links to dead workbooks & delete.
Welcome to the board!

If you change the cell format to text then you could do it with data validation, setting the criteria as text lengh / equal to / 4

With a numeric format I can't see any way to validate the leading zero(s).
 
Upvote 0
Thanks for the welcome and your quick reply!

I think the data needs to stay a number - and not text - as it gets imported into some other databases.

If anyone has any other suggestions, I'd love to hear them.

Thanks again!
 
Upvote 0
Maybe

Data>Data Validation

Integer Number
is between
Minimum
1000
Maximum
9999

Edit
sorry, i misread your post.
Sometimes you have to enter
0567
0123
and so on

HTH

M.
 
Last edited:
Upvote 0
Hi David,

Welcome to the board, David! Not only are you a first-time poster, but I'm about to become a first-time solution attempt poster! How befitting! ;)

The previous 2 suggestions are a good start. So, I propose a 2-part solution, if it might work for you. I'm using Excel 2007. Please forgive me if I provide too much detail, as I don't know your level of Excel expertise, and it may prove to be useful to others.

Let's use column B for user entry and Column A to return the final coerced value. Column A could be 'hidden' if you don't want your users to see it and become confused. However, you must have an empty column immediately to the left of the user input column (Column B) to receive the final 'non-text' values. When you finally apply this to your production workbook, you may desire to copy any existing 4 digit values in the 'user input' column into Column A first. This solution is for one entry at a time, not a list of values to be pasted into place.

Part 1: Prepare formatting and data validation

  • Highlight Column B and format as 'text'
  • Select Cell B2, hold Shift key and PgDn as far as you want to go to allow user entries.
  • Click Data tab on ribbon bar, select Data Validation > Data Validation
  • In Settings, choose Allow: 'Text Length' Leave 'ignore blanks' checked
  • Data: 'equal to'; Length: '4'
  • Click 'Error Alert' tab. In 'Title' enter: 'Invalid Entry'; in 'Error Message' enter: 'You must enter exactly 4 numerical digits!' (yes, I know that's redundant...we're working with users here!!! ;) ) Click OK
All you have done in Part 1 is ensure a user can only enter exactly 4 characters from the keyboard and prepare the user entry column for input. In Part 2, I'll provide VBA code to further validate the user entry.

Part 2: Worksheet_Change code for input worksheet

Copy all of the following code, open the VB Editor (Alt-F11), under Microsoft Excel Objects, double-click the name of the worksheet (initially a test workbook/worksheet) you're using in the upper left-hand window, paste code into upper right-hand window.

Code:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
'The code only works for one cell at a time
'Column B (Column 2) is for user input.  The result of the formula below will display in Column A on same row
If Target.Column <> 2 Then Exit Sub 'must be Col B
If Target.Row = 1 Then Exit Sub 'Cannot be Row 1, header row.
Application.EnableEvents = False
If Trim(Target.Value) = Empty Then
    Target.Value = ""                   'if user deletes entry in target cell
    Target.Offset(0, -1).Value = ""     'if user deletes entry, also clear Column A value on same row
    GoTo Reset
End If
If IsNumeric(Target.Value) = False Then GoTo Warning        'if entry is not numeric, issue warning
    Application.EnableEvents = False
    'Since it's possible to add a "+/-" sign in front of 3 digits creating a valid 4 character numeric expression,
    'eliminate possiblity
    If Left(Target.Value, 1) = "+" Or Left(Target.Value, 1) = "-" Then GoTo Warning
    With Target.Cells
        .HorizontalAlignment = xlRight                      'right align target cell for appearance
    End With
    If Target.Value < 10000 And Target.Value <> 0 Then      'expression must be 9999 or less, but not 4 zeros
    Target.Offset(0, -1).NumberFormat = "0000"              'special formatting for 4 digit result
    Target.Offset(0, -1).Formula = Right(Target.Value, Len(Target.Value))   'don't laugh; it works!
    GoTo Reset
End If
Warning:
    Application.EnableEvents = False
' If user enters exactly 4 characters, but one or more characters are not numeric,
' warn user and remove their entry attempt
    MsgBox ("You must enter exactly 4 numerical digits" _
    & vbNewLine & "If the leading digit(s) are zeros," _
    & vbNewLine & "You must include them too!" _
    & vbNewLine & "Please retry your entry!"), vbCritical
    Target.Value = ""                                       'delete invalid target cell entry
    Target.Offset(0, -1).Value = ""                         'delete entered value from Column A
    Target.Cells.Select                                     're-select target cell
Reset:
Application.EnableEvents = True                             're-enable events
End Sub

BTW: when you are done, make sure you save the workbook as macro-enabled.

Test by entering keystrokes in any cell starting with Cell B2 and going south. Valid results will be captured in Column A, same row.

Note: select any data validated, user input cell in column B. On the ribbon bar, home tab, note the word 'Text' above the 'Number' section. Now, select a cell in Column A that displays a result. Note that the format is 'Special'. Right click on cell, format cells and you'll see it's a Type: ZipCode. Click Cancel. However, I've used the result in formulas in Column E, for instance, as a number; calculations are valid and this formula cell is also becomes type: special. I suspect that data will work downstream from you.

I've tested many combinations of symbols (including +/-), letters, and numbers (including leading zeros) and so far, it has validated correctly. See my additional comments in the code to help explain its logic.

Disclaimer: always test new code on a test workbook first before using in a production environment!

Please let me know if this is an acceptable solution for you and if you encounter any errors you don't expect.

-dougbert
 
Upvote 0
It's so important to post which version of Excel you have so we can give you appropriate instructions. I'll assume you have Excel 2010

Try this example...
• Select cells A1:A10, with A1 as the active cell
• Home.Format.Cells...Number_tab
...Category: TEXT
...Click: OK

• Data.Data_Validation.Data_Validation
...Settings_Tab
......Allow: Custom
......Formula: =AND(LEN(A1)=4,--A1>=0,--A1<=9999,ISERROR(FIND(".",A1)))
...Error_Alert_Tab
......Title: Invalid Entry
......Error Message: You must enter exactly 4 digits
......Click: Ok

Is that something you can work with?

EDITED TO INCLUDE THIS COMMENT
This validation formula may be better:
=AND(LEN(A1)=4,ISNUMBER(--MID(A1,1,1)),ISNUMBER(--MID(A1,2,1)),ISNUMBER(--MID(A1,3,1)),ISNUMBER(--MID(A1,4,1)))
 
Last edited:
Upvote 0
Try using Ron's validation formula

=AND(LEN(A1)=4,ISNUMBER(--MID(A1,1,1)),ISNUMBER(--MID(A1,2,1)),ISNUMBER(--MID(A1,3,1)),ISNUMBER(--MID(A1,4,1)))

With this code to switch the the cell format, note that this code must be in the worksheet module (right click sheet tab > view code).

I've assumed entry in column B only, starting in B2.

Code:
Private Sub Worksheet_Change(ByVal Target As Range)
With Target
    If IsEmpty(.Value) And .Row = 1 Or .Column <> 2 Or .Count > 1 Then Exit Sub
        .NumberFormat = "0000"
        .TextToColumns Destination:=Target, DataType:=xlFixedWidth, FieldInfo:=Array(0, 1)
End With
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Static oldtarget As Range
    With Target
        If .Row = 1 Or .Column <> 2 Or .Count > 1 Then Exit Sub
           .NumberFormat = "@"
            If Not oldtarget Is Nothing And Not IsEmpty(oldtarget.Value) Then
                With oldtarget
                    .NumberFormat = "0000"
                    .TextToColumns Destination:=oldtarget, DataType:=xlFixedWidth, FieldInfo:=Array(0, 1)
                End With
            End If
    End With
Set oldtarget = Target
End Sub
 
Upvote 0
Just found a bug in the code in my previous post, corrected below

Code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Static oldtarget As Range
If Not oldtarget Is Nothing Then
    If Not IsEmpty(oldtarget.Value) Then
        With oldtarget
            .NumberFormat = "0000"
            .TextToColumns Destination:=oldtarget, DataType:=xlFixedWidth, FieldInfo:=Array(0, 1)
        End With
    End If
End If
With Target
    If .Row = 1 Or .Column <> 2 Or .Count > 1 Then Exit Sub
       .NumberFormat = "@"
        Set oldtarget = Target
End With
End Sub

edit: the previous code with the bug contains 2 procedures, Worksheet_Change and Worksheet_SelectionChange, this one does the job of both.
 
Last edited:
Upvote 0
Wow! Thanks everyone for all your help and suggestions...this board is awesome!

Will play around with things at work tomorrow. Ron, your validation formula seems spot-on. Thanks!

(And, yes, I have Excel 2010)
 
Upvote 0

Forum statistics

Threads
1,224,595
Messages
6,179,798
Members
452,943
Latest member
Newbie4296

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top