Did you try and figure out why it wasn't working properly? I've amended the code, this should do what you want.I know the code is sorely lacking in comments, so why don't you spend some time stepping through the code to try and understand how it works. You may surprise yourself and come up with a better way to do it.VB Code:
Option Explicit Dim IsNegative As Boolean Private Sub Text1_Change() If Left$(Text1.Text, 1) = "-" Then Text1.MaxLength = 3 IsNegative = True Else Text1.MaxLength = 2 IsNegative = False End If End Sub Private Sub Text1_KeyPress(KeyAscii As Integer) Select Case KeyAscii Case vbKey0 To vbKey9 ' These keys are OK If Len(Text1.Text) = 1 Then If Not IsNegative Then If Val(Text1.Text) > 4 Then KeyAscii = 0 ElseIf Val(Text1.Text) = 4 Then If KeyAscii > vbKey0 Then KeyAscii = 0 End If End If End If Else If Abs(Val(Text1.Text)) > 2 Then KeyAscii = 0 ElseIf Abs(Val(Text1.Text)) = 2 Then If KeyAscii > vbKey0 Then KeyAscii = 0 End If End If End If Case 45 ' 45 is '-' If Len(Text1.Text) > 0 Then KeyAscii = 0 End If Case vbKeyBack, vbKeyDelete ' Allow backspace & delete Case Else KeyAscii = 0 End Select End Sub
BTW There is still a subtle logic error in the code. See if you can figure out what it is and then fix it.




Reply With Quote