Logo 
Search:

MS Office Forum

Ask Question   UnAnswered
Home » Forum » MS Office       RSS Feeds

text box -- integers only

  Asked By: Karina    Date: Dec 20    Category: MS Office    Views: 1071
  


Is it possible to set a text box on a form to accept integers only? Any
help would be appreciated. Thanks very much.

Share: 

 

5 Answers Found

 
Answer #1    Answered By: Cesara Fernandez     Answered On: Dec 20

The following VBA code attached to a textbox will allow entry of digits (0 to 9)
only. Change TextBox1 throughout to the name of your textbox.

Private Sub TextBox1_Change()
If Len(TextBox1.Text) > 0 Then
TextBox1.Text = NbrOnly(TextBox1.Text)
End If
End Sub

Private Function NbrOnly(Intxt As String) As String
Dim zz As Long, OutStr As String
For zz& = 1 To Len(Intxt$)
Select Case Mid(Intxt$, zz&, 1)
Case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
OutStr$ = OutStr$ & Mid(Intxt$, zz&, 1)
Case Else
'do nothing
End Select
Next zz&
NbrOnly$ = OutStr$
End Function

 
Answer #2    Answered By: Daimon Jones     Answered On: Dec 20

BTW, can you show me how to modify this code to allow for only 1
digit entries? Thanks. (I sent an earlier message thanking you, but I
don't see it in the list. Anyway, I really appreciate the help.)

 
Answer #3    Answered By: Aabirah Khan     Answered On: Dec 20

You can also use the "isnumeric" function in the following way:
If IsNumeric(TextBox1.Text) Then
MsgBox "OK"
Else
MsgBox "no good"
End If

You can limit entry to maximum one digit by changing the "maxlength" property
of your textbox to 1. You can access the properties menu in the VBEditor. If it
is not already displayed press the F4 key. Be sure that you change the property
of your textbox1 control.

 
Answer #4    Answered By: Utsav Shah     Answered On: Dec 20

I used the isnumeric feature as follows:

Private Sub textbox1_Change()
If IsNumeric(TextBox1.Value) = False Then TextBox1.Value = ""
End Sub

This eliminates the message box  and just clears the textbox whenever
anything other than a numbe is entered. And I used the maxlength
property on the ones where I wanted to limit the length.

Cool.

Plus, I figured out the Select Case feature from Hutch's answer which
I could also use to restrict answers as follows:

Select Case TextBox.Value
Case 2,4,6,8
TextBox.Value = TextBox.Value
Case Else
TextBox.Value = ""
End Select

 
Answer #5    Answered By: Ziza Mizrachi     Answered On: Dec 20

Great solution! I imagine I'll be studying up on WHY it works for
some time, but meanwhile, this does exactly what I was hoping for.
Thanks very much.

 
Didn't find what you were looking for? Find more on text box -- integers only Or get search suggestion and latest updates.




Tagged: