Just figured I would mention that users will still be able to paste in
invalid data, so a more thorough check of the entry will still be
necessary. This type of problem (restrict entry to certain characters)
came up many times over in the compiled VB newsgroups where I
originally
frequented a lot. Here is a modification of the routine I used to post
which handles digits only (no decimal point, although a routine for
that
can be created if needed) and an optional single trailing percent sign
and
which will not let a user paste bad data in. All the following code
should
be copy/pasted exactly as is into the UserForm code window.
'******************** START OF CODE ********************
Dim LastPosition As Long
Private Sub TextBox1_Change()
Static LastText As String
Static SecondTime As Boolean
If Not SecondTime Then
With TextBox1
If .Text Like "*[!0-9%]*" Or .Text Like "*%?" Or _
.Text Like "*%*%*" Or .Text = "%" Then
Beep
SecondTime = True
.Text = LastText
.SelStart = LastPosition
Else
LastText = .Text
End If
End With
End If
SecondTime = False
End Sub
Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As
_
Integer, ByVal X As Single, ByVal Y As Single)
With TextBox1
LastPosition = .SelStart
'Place any other MouseDown event code here
End With
End Sub
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
With TextBox1
LastPosition = .SelStart
'Place any other KeyPress checking code here
End With
End Sub
'******************** END OF CODE ********************
Rick
Hi Amit,
You can use the KeyPress event of the TextBox to check each
character
as it's entered and either accept it or reject it. In the example
below,
numbers, the % symbol and backspace are allowed, while all other
characters are cancelled.
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case 8, 37, 48 To 57
''' Backspace, % and numbers are all OK
Case Else
''' Cancel all other characters.
KeyAscii = 0
End Select
End Sub
Even with this event in place you'll still need to do some
additional
validation in your Submit button click event to trap for the few
situations where the user can still enter invalid data, like 12%3 or
just
%.
--
Rob Bovey, Excel MVP
Application Professionals
http://www.appspro.com/
* Take your Excel development skills to the next level.
* Professional Excel Development
http://www.appspro.com/Books/Books.htm
hi - I have a user entry text box to enter a % value...and a submit
command
button which mutiplies the entry with another number. i'm able to
take
inputs
both as % and as whole numbers and based on the input..either remove
the
% or
if whole number then divide by 100. i would like to put a change
event
which
catches any input other than numers or %....valid entries would be
100%
or
100.....need help with being able to catch entries like rree or rr%
any help much appreciated.
regards,
Amit