Excel VBA Text Box Limit Error

If the text field is empty and I click the backspace button, it crashed and the highlighted line

TB1 = Left (TB1, Len (TB1) - 1)

what can i change to stop this glitch

Private Sub TB1_Change()
Dim strStrings As String, LastLetter As String
Application.EnableEvents = False
LastLetter = Right(TB1, 1)
strStrings = ","
If InStr(1, strStrings, LastLetter) > 0 Then
    MsgBox LastLetter & " not allowed"
    TB1 = Left(TB1, Len(TB1) - 1)
End If
Application.EnableEvents = True

End Sub

This is a text box where "," is limited.

+4
source share
1 answer

Use the following subsection.

Private Sub TB1_Change()
On Error GoTo HarunErrHandler
Dim strStrings As String, LastLetter As String

    If TB1 = "" Then
        Exit Sub
    End If

    Application.EnableEvents = False
        LastLetter = Right(TB1, 1)
        strStrings = ","
        If Val(InStr(1, strStrings, LastLetter)) > 0 Then
            MsgBox LastLetter & " not allowed"
            TB1 = Left(TB1, Len(TB1) - 1)
        End If
    Application.EnableEvents = True

Exit Sub
HarunErrHandler:
MessageBox = MsgBox("Error Number: " & Err.Number & vbCrLf & Err.Description, vbCritical, "Error")
End Sub
+6
source

Source: https://habr.com/ru/post/1628063/


All Articles