Userform Textbox - prevent special characters

sharky12345

Well-known Member
Joined
Aug 5, 2010
Messages
3,421
Office Version
  1. 2016
Platform
  1. Windows
Can someone assist me with some code that will only allow numerics and letters in a userform textbox?

I don't want people to be able to enter anything other than those and perhaps a space and I'd like the restriction as they type please.
 

Excel Facts

Enter current date or time
Ctrl+: enters current time. Ctrl+; enters current date. Use Ctrl+: Ctrl+; Enter for current date & time.
Hi, thanks for the reply - that doesn't seem to do what I need though.
 
Upvote 0
Can someone assist me with some code that will only allow numerics and letters in a userform textbox?

I don't want people to be able to enter anything other than those and perhaps a space and I'd like the restriction as they type please.
Put the following code in the UserForm's code module...
Code:
[COLOR="#008000"][B]' Note: This Dim statement must be located
        above any other code procedures[/B][/COLOR]
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-9A-Za-z ]*" Then
        Beep
        SecondTime = True
        .Text = LastText
        .SelStart = LastPosition
      Else
        LastText = .Text
      End If
    End With
  End If
  SecondTime = False
End Sub

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
  LastPosition = TextBox1.SelStart
End Sub

Private Sub TextBox1_MouseDown(ByVal Button As Integer, _
            ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
  LastPosition = TextBox1.SelStart
End Sub
 
Last edited:
Upvote 0

Forum statistics

Threads
1,223,246
Messages
6,170,988
Members
452,373
Latest member
TimReeks

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top