1

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:

enter image description here

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 ?

1
  • Your Left function will fail with that error if the textbox length is less than 2 which is possible for 2 of your tests. Commented Dec 8, 2022 at 9:03

1 Answer 1

0

You have to run the isNumeric-check first - otherwise it could happen, that you compare a string to a number - which fails.

I would use an extra function for this:

Private Function isDayValueOK(value As Variant) As Boolean

If Not IsNumeric(value) Then Exit Function
'If Len(value) > 2 Then Exit Function 'you don't need this because then the number is greater than 100 and greater than 31.
If value > 31 Then Exit Function

isValueOK = True

End Function

You can then call this function like this: If isDayValueOK(Me.txtDay.Value) = false then ...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.