How do you limit characters typed in a textbox?

The code I have warns you when you go over 150 characters, but it still allows a user to type in the character showing a negative number in the label. How do I limit that?
Private Sub Text1_KeyPress(KeyAscii As Integer)
    Dim a As Integer
    a = 150 - Len(Text1.Text)
    
    If a = 1 Then
        Call MsgBox("Oops! You've gone past 150 characters!", vbExclamation Or vbSystemModal, App.Title)
        lblChar.Caption = "char:" & a
    Else
        lblChar.Caption = "char:" & a
    End If
End Sub

Open in new window

Takamine334Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

appariCommented:

set the maxlength property of the textbox to 150
0
Jaime OlivaresSoftware ArchitectCommented:
you can do something like:
Private Sub Text1_KeyPress(KeyAscii As Integer)
    Dim a As Integer
    a = 150 - Len(Text1.Text)
    
    If a = 1 Then
        Call MsgBox("Oops! You've gone past 150 characters!", vbExclamation Or vbSystemModal, App.Title)
        lblChar.Caption = "char:" & a
        Text1.Text = LEFT(Text1.Text, 150)
    Else
        lblChar.Caption = "char:" & a
    End If
End Sub

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Jaime OlivaresSoftware ArchitectCommented:
but it will be better:

 If a < 1 Then

because there is a chance to add more than 1 character at a time (using Paste option), and a will be lower than 1
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic Classic

From novice to tech pro — start learning today.