I have the following script that allows only integers up to 31, lenght of the string not more than 2 and has to be a numeric value.
If that is not met i want to delete the last inserted value(so that the user is not able to insert any of these inputs).
Private Sub txtDay_Change()
If Me.txtDay.Value > 31 Or Len(Me.txtDay.Value) > 2 Or Not IsNumeric(Me.txtDay.Value) Then
Me.txtDay.Value = Left(Me.txtDay.Value, Len(Me.txtDay.Value) - 1)
Cancel = True
Else
Sheets("do not open!").Range("C1") = Me.txtDay.Value
End If
The issue is that if I insert a text or hit backspace then i get the following error:
What I did to resolve this is by applying an On error GoTo
Private Sub txtDay_Change()
On Error GoTo er
If Me.txtDay.Value > 31 Or Len(Me.txtDay.Value) > 2 Or Not IsNumeric(Me.txtDay.Value) Then
Me.txtDay.Value = Left(Me.txtDay.Value, Len(Me.txtDay.Value) - 1)
Cancel = True
Else
Sheets("do not open!").Range("C1") = Me.txtDay.Value
End If
er:
Cancel = True
It seems to work find now. but would anyone know if this would be a good approach? and would anyone know why this is happening ?

Leftfunction will fail with that error if the textbox length is less than 2 which is possible for 2 of your tests.