Home » excel » excel – Character count VBA Userform

excel – Character count VBA Userform

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have created a userform and a label (label 39). The purpose of this textbox is to auto-update every time a user inputs a character into a textbox (Textbox 7).

The reason I have to do this is to ensure that users input a max of 120 characters.

To do this I have written this code:

Private Sub TextBox7_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Me.Label39 = Len(Me.TextBox7.Value)
End Sub

The issue with this is it starts with 0 with the first letter. Therefore, if you type “Mary”, the counter will show 3 instead of 4. This will confuse my users.

So I thought of doing this instead:

Private Sub TextBox7_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Me.Label39 = Len(Me.TextBox7.Value) + 1
End Sub

This seems to solve the issue. However, once you reach the maximum limit, 120 characters then the users will face a problem as this will not be submitted to the SQL Table.

Is there any clever work around?

Cheers

How to&Answers:

Textboxes have an attribute called “MaxLength”. Change the value of this to 120 and it will lock the user to inputting up to 120 characters