Link to home
Start Free TrialLog in
Avatar of rhariz
rhariz

asked on

Character Prevention

How do I prevent a user from using , (comma) or " (quotes) in a text box.
Avatar of rhariz
rhariz

ASKER

null
Avatar of rhariz

ASKER

Edited text of question.
You can capture the text change event for the text box.


Private Sub Text1_Change()
    Dim myText As String
    Dim testText As String
    Dim char As String
    Dim i As Long
   
    If InStr(Text1.Text, ",") Or InStr(Text1.Text, """") Then
        testText = Text1.Text
        For i = 1 To Len(testText)
            char = Mid(testText, i, 1)
            If char <> "," And char <> """" Then
                myText = myText & char
            End If
        Next i
        Text1.Text = myText
    End If
End Sub
Same as other post but now commented

Option Explicit
Private Sub Text1_Change()
    Dim myText As String
    Dim testText As String
    Dim char As String
    Dim i As Long
   
    'Test to see if any invalid charachters are being used
    If InStr(Text1.Text, ",") Or InStr(Text1.Text, """") Then
        testText = Text1.Text
       
        'Loop though all of the charachters in the string
        For i = 1 To Len(testText)
       
            'Grab one charachter at a time
            char = Mid(testText, i, 1)
           
            'If it isn't an offending charchter, keep it
            If char <> "," And char <> """" Then
                myText = myText & char
            End If
        Next i
       
        'Replace the value in the text box with our value
        Text1.Text = myText
    End If
End Sub
This code is a little smaller and you won't loose your cursor position.

Private Sub Text1_KeyUp(KeyCode As Integer, Shift As Integer)
    Dim position As Long
    If KeyCode = 188 Or KeyCode = 222 Then
        position = Text1.SelStart
        Text1.Text = Mid(Text1.Text, 1, Text1.SelStart - 1) & Mid(Text1.Text, Text1.SelStart + 1)
        Text1.SelStart = position - 1
    End If
End Sub
Here is what'll do it efficiently:

Private Sub Text1_KeyPress(KeyAscii As Integer)
  ' ASCII code of comma is 44, that of quotes is 34.
  ' But it won't be a good idea to hardcode the codes!
  If KeyAscii = Asc("""") Or KeyAscii = Asc(",") Then
    KeyAscii = 0
  End If
End Sub
ASKER CERTIFIED SOLUTION
Avatar of ggilman
ggilman

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rhariz

ASKER

Can't allow the characters to be pasted.
Avatar of rhariz

ASKER

Works like a charm.  This is great that you caught the cursor position moving.  I noticed that in memo fields the cursor moved to the beginning of the line when attempting to insert quotation marks.