Home > OS >  VBA Userform invalid procedure textbox
VBA Userform invalid procedure textbox

Time:12-09

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 ?

CodePudding user response:

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 ...

  • Related