ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Text Box - Restricting Entry (https://www.excelbanter.com/excel-programming/305596-text-box-restricting-entry.html)

Paul W Smith[_3_]

Text Box - Restricting Entry
 
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



Jim Cone

Text Box - Restricting Entry
 
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 W Smith" wrote in message ...
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



mrt

Text Box - Restricting Entry
 
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

"Paul W Smith" wrote:

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





All times are GMT +1. The time now is 07:05 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com