Userform Data Validation

bethaneesmith

New Member
Joined
Nov 12, 2014
Messages
4
I need the text box in the userform to accept only alphabet letters. This is the code I have so far but it only accepts 2 letters. Also, the message box telling the user to only enter letters pops up when the userform is initialized and after the text is inputted. How do I fix this?

Private Sub TextBox1_Change()
If Not TextBox1.Value = vbNullString _
And Not TextBox1.Value Like "[A-Z]" _
And Not TextBox1.Value Like "[a-z]" _
And Not TextBox1.Value Like "[A-Z][A-Z]" _
And Not TextBox1.Value Like "[a-z][a-z]" _
And Not TextBox1.Value Like "[A-Z][a-z]" _
And Not TextBox1.Value Like "[a-z][A-Z]" Then
TextBox1.Value = vbNullString
MsgBox "Enter only letters.", 0, vbNullString"
End If
End Sub
 

Excel Facts

Copy formula down without changing references
If you have =SUM(F2:F49) in F50; type Alt+' in F51 to copy =SUM(F2:F49) to F51, leaving the formula in edit mode. Change SUM to COUNT.
Hi bethaneesmith, welcome to the forum. To check the strings, using Regular Expression is handy as follows.

Code:
Private Sub TextBox1_Change()
     Dim oReg As Object
     Set oReg = CreateObject("VBScript.RegExp")
     oReg.Pattern = "[^a-zA-Z]"
     If Not oReg.Test(TextBox1.Value) = False Then
     TextBox1.Value = Left(TextBox1.Value, Len(TextBox1.Value) - 1)
         MsgBox "Enter only letters.", 0
     End If
     Set objRE = Nothing
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,162
Messages
6,170,431
Members
452,326
Latest member
johnshaji

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