vbams-accessms-officevba7vba6

How to Find how many Letters does a Text Box's value has in VBA?


I Wish there is a way to get the amount of the characters of a Text Box Value so I can limit it to be the amount that I wanted. so like when someone entered 134131323 as the Year of Date, I can limit it to 4 characters.

Also I the programming language is VBA and I do it in Microsoft Access.

I Did try to get it working with doing txtTest.Value.Characters idk but that did not work obviously and I DID SEARCH THE WHOLE INTERNET but I did not get A SINGLE RISULT. I Am a noob so someone help


Solution

  • Use the AfterUpdate event of the textbox:

    Private Sub YourTextbox_AfterUpdate()
    
        Const MaxLength As Integer = 4
        Dim Text        As String
        
        Text = Nz(Me!YourTextbox.Value)
        
        If Len(Text) > MaxLength Then
            Me!YourTextbox.Value = Left(Text, MaxLength)
        End If
    
    End Sub