PDA

View Full Version : Solved: Restrict Text Box



khalid79m
01-24-2011, 08:02 AM
Hi I have a text box in a form.. i want to ensure no special characters can be put in especially "|" just accept letters and numbers, full stops and comas.

gcomyn
01-24-2011, 08:20 AM
here is a function that I just cobbled up that you can use in an if statement like :


if not Check_Special(me.txtText.value) then
MsgBox "You have entered a special character" ' or whatever you want if it has a special character
end if

here is the function:


Public Function Check_Special(strTemp As String) As Boolean
Dim strStrings As String
Dim x As Integer

strStrings = "~`|@#$%^&*()_+!<>?:;'""" 'put in whatever special characters you don't want in the string

For x = 1 To Len(strTemp)
If InStr(1, strStrings, Mid(strTemp, x, 1)) > 0 Then
Check_Special = False
Exit Function
End If
Next
Check_Special = True
End Function

GComyn
:sleuth:

GTO
01-24-2011, 09:16 AM
Just another possibility:


Option Explicit

Private Sub TextBox1_Change()
Static REX As Object

If REX Is Nothing Then
Set REX = CreateObject("VBScript.RegExp")
With REX
.Global = True
.Pattern = "[^a-zA-Z0-9\.\,]"
End With
End If

TextBox1.Value = REX.Replace(TextBox1.Value, vbNullString)
End Sub

You might want to look at post #5 of: http://www.vbaexpress.com/forum/showthread.php?t=35742

...as well.

Hope that helps,

Mark

JP2112
01-24-2011, 01:04 PM
Wouldn't it be better to simply alert the user that they've entered invalid characters (perhaps when clicking "Submit", change the background of the textbox to red and pop up a msgbox), instead of making them disappear as they're typed? Just saying.

mdmackillop
01-24-2011, 01:15 PM
A mixture of the above to advise & remove illegals


Private Sub TextBox1_Change()
Dim strStrings As String, LastLetter As String

Application.EnableEvents = False
LastLetter = Right(TextBox1, 1)
strStrings = "\/~`|@#$%^&*()_+!<>?:;'"""
If InStr(1, strStrings, LastLetter) > 0 Then
MsgBox LastLetter & " not allowed"
TextBox1 = Left(TextBox1, Len(TextBox1) - 1)
End If
Application.EnableEvents = True
End Sub

khalid79m
03-28-2011, 01:03 PM
Excellent thanks :)