PDA

View Full Version : Solved: specific lentgh for a textbox



mariusc
01-19-2011, 08:08 AM
Hello,

I have an empty textbox in a userform. How can I setup a specific length (13 numbers) for textbox, if user will complete this textbox, without making this textbox mandatory to complete? There is a posibility that user will not complete this textbox, that`s why I do not want to make it mandatory to complete.

Thank you

shrivallabha
01-19-2011, 08:33 AM
I had previously used a code to set maximum length with alert message.

Private Sub TextBox1_Change()
If Len(TextBox1.Value) > 4 Then
MsgBox "Only 4 characters are allowed!"
TextBox1.Value = Left(TextBox1.Value, 4)
TextBox1.SetFocus
End If
End Sub

mikerickson
01-19-2011, 08:42 AM
You might use the .MaxLength property of the textbox.

mariusc
01-19-2011, 09:43 AM
I already setup the property maxlength with value 13.
Also, for that textbox i have this code :

Private Sub txtCNP_Change()
Static REX As Object

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

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

CNP = numeric personal code.
This CNP must have only 13 characters,numbers only.
And with the earlier code, i manage to solve this issue : only numbers can bo completed into this textbox.
Now I need to set up somehow this textbox to accept only 13 numbers, not 12 or 14.
MaxLength it is already setup to 13.
MinimumLength does not exist and when the userform is launched, this textbox is empty. I do not need to make it mandatory to complete,but in case user will complete, I do not want him to go wrong ( he can write only 12 numbers). How to do that?

shrivallabha
01-19-2011, 09:51 AM
You can use Len attribute as


If Len(TextBox1.Value) <> 13 Then
MsgBox "Please provide complete CNP!"
TextBox1.SetFocus
End If

GTO
01-19-2011, 09:57 AM
Hi again,

Please see Mike's suggestion at your other thread: http://www.vbaexpress.com/forum/showthread.php?t=35742 reference dis-allowing non numerics.

Reference 13 in length or disallow entry, maybe try the Exit event:


Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Not Len(TextBox1.Value) = 13 Then
If MsgBox("You must enter 13 digits! Would you like to modify your current" & vbCrLf & _
"entry? If so, click <Yes>, else click <No> and the box will empty.", _
vbYesNo + vbQuestion, _
vbNullString) = vbYes Then

Cancel = True
Else
TextBox1.Value = vbNullString
End If
End If
End Sub

Hope that helps,

Mark

mariusc
01-19-2011, 11:45 PM
Thank you, Mark, once again.
This is what I need.