restricting input characters

  • Thread starter Thread starter Bri
  • Start date Start date
B

Bri

As part of a macro, I open an input box. Here is the part I'm not sure how
to code: I'd like the input to be restricted to either 1 or 2 alphanumeric
characters ONLY. (no spaces, other symbols, >=3 characters, etc.)

1, Ab, 4G, are all OK.
#4, 1 2, A3b are not OK.

Could someone offer a few clues?

Thanks
Bri
 
I wouldn't use an input box - use a user form, which has keypress
events - which means you can restrict the key's being pressed by code.
You can also restrict the input length to the two characters you want.
 
assuming to use input box, i'm not sure this one would satisfy you. but
try this.

Sub testme()
Dim strprompt As String
Dim flg As Boolean
Dim sdata As String
Dim res

strprompt = "input only alphanumeric"
flg = True
sdata = "0123456789abcdefghijklmnopqrstuvwxyz"

Do While flg
res = Application.InputBox(strprompt, _
Default:=res, Type:=3)
If VarType(res) = vbBoolean Then
Exit Sub
ElseIf Len(res) = 1 Then
If InStr(sdata, Left(LCase(res), 1)) _
flg = False
Else
strprompt = _
"Wrong Data!! Not alphanumeric"
End If
ElseIf Len(res) = 2 Then
If InStr(sdata, Left(LCase(res), 1)) > 0 _
And InStr(sdata, Right(LCase(res), 1)) _
strprompt = "Wrong Data!!"
flg = False
Else
strprompt = _
"Wrong Data!! Not alphanumeric"
End If
Else
strprompt = _
"Wrong Data!! Too many characters"
End If
Loop
MsgBox res
End Sub
 
Insert a user form into your module

Insert a text box - use the properties to set maxlength at 2

in code use

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii < 48 Or KeyAscii > 122 Then KeyAscii = 0
If KeyAscii > 57 And KeyAscii < 65 Then KeyAscii = 0
If KeyAscii > 90 And KeyAscii < 97 Then KeyAscii = 0
End Sub


This will allow upper and lower case and numbers ONLY, and a maximum
length of 2
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top