Link to home
Start Free TrialLog in
Avatar of RWayneH
RWayneHFlag for United States of America

asked on

Userform Textbox Char counter

I would like to add a character counter in a userform that monitors text going into a textbox.  I have a limit of number that can be used.. and I would like user to know how many they have left as they are typing in the textbox.  Is this possible?  If so, what would go in the: Private Sub Textbox1_Change() that would link to a Label that would chg..
SOLUTION
Avatar of Shums Faruk
Shums Faruk
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RWayneH

ASKER

Both great, options..  as a related question, if the char limit is exceeded, I want to chg the Caption on the OK button, and as it stays within char limit keep it as is or = OK  Is this a change() for the OK button?
Try Something like below:
Private Sub TextBox1_Change()
Dim RemText As Integer, TextCount As Integer
TextCount = 10
RemText = TextCount - TextBox1.TextLength
Label1.Caption = RemText
If TextBox1.TextLength > TextCount Then
    MsgBox "Text Exceeded", vbOKCancel
End If
End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RWayneH

ASKER

Thanks to all, great options to use.
I think it is more professional to disable the commandbutton if the max is exceeeded.

Option Explicit

Private Sub TextBox1_Change()
Const MaxLength As Integer = 20

Me.Label1.Caption = "Characters left: " & MaxLength - Len(Me.TextBox1.Text)

Me.CommandButton1.Enabled = Len(Me.TextBox1.Text) - (MaxLength - 1)
End Sub

Open in new window

You're welcome! Glad we could help.
@Roy

I took care of that in my solution. The length of text will not exceed the MaxCharLength set in the code.
Subodh

I didn't see your post until after I posted, but my code disables the button if the character length is exceeded, which would prevent the button being clicked
Typo in my last code, should be

Private Sub TextBox1_Change()
Const MaxLength As Integer = 20

Me.Label1.Caption = "Characters left: " & MaxLength - Len(Me.TextBox1.Text)

Me.CommandButton1.Enabled = Len(Me.TextBox1.Text) <= (MaxLength - 1)
End Sub

Open in new window