Text Box - Restricting Entry

  • Thread starter Thread starter Paul W Smith
  • Start date Start date
P

Paul W Smith

I want to restrict the entries that are allowed in a text box to just the
numbers 1 to 11.

I have fiddled around with the KeyDown, KeyUp, and KeyPress events, only
allowing entries with ASCII codes between 48 and 56.

However I cannot get it right. Can any expert VB programmers please supply
the necessary code.

Paul Smith
 
Paul,

There may be better ways of doing this but the following seems to work...
'------------------------------------
Private Sub TextBox1_Change()
If Val(TextBox1.Value) = 0 Then
TextBox1.Value = vbNullString
ElseIf Len(TextBox1.Value) > 1 Then
If Val(TextBox1.Value) > 11 Then TextBox1.Value = Left$(TextBox1.Value, 1)
End If
End Sub

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Dim strChar As String
strChar = Chr$(KeyAscii)
If strChar Like "[!0-9]" Then KeyAscii = 0
End Sub
'------------------------------------

Regards,
Jim Cone
San Francisco, CA
 
Paul i think the next code would do the trick, if i understand your problem correctly

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
'only accept nummbers from 0 to 9
If KeyAscii > 47 And KeyAscii < 58 Then
'In case nothing is in textbox not alouwd to put in 0
If KeyAscii = 48 And TextBox1.Text = "" Then
KeyAscii = 0
End If
'If there is already a number in the textbox
If Len(TextBox1.Text) = 1 Then
'The number in the textbox is a 1
If TextBox1.Text = 1 Then
'only 1 and 0 are ok
If KeyAscii > 49 Then
KeyAscii = 0
End If
Else
KeyAscii = 0
End If
End If
'if there are already 2 numbers in the box then this is the maximum
If Len(TextBox1.Text) = 2 Then
KeyAscii = 0
End If
Else
'It is not a number
KeyAscii = 0
End If
End Sub

Good Luck
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top