Backspace Error

latex88

Registered User.
Local time
Today, 15:22
Joined
Jul 10, 2003
Messages
198
I downloaded a touchscreen keypad form somewhere online. When I backspace the characters in the text field one too many times, meaning when there are no more characters to backspace, I get an error message (Run-time error '5') or "Invalid procedure call or argument" and the below line is highlighted in the VBA code. How do I go about fixing this problem?

Me.Controls(Screen.ActiveControl.Name).Value = Left(Me.Controls(Screen.ActiveControl.Name).Value, Len(Me.Controls(Screen.ActiveControl.Name)) - 1)


FYI. Below is the entire backspace procedure

Private Sub Key_Backspace_Click()
Screen.PreviousControl.SetFocus
Me.Controls(Screen.ActiveControl.Name).SelStart = Nz(Len(Me.Controls(Screen.ActiveControl.Name)), 0)
Me.Controls(Screen.ActiveControl.Name).SelLength = 0
Me.Controls(Screen.ActiveControl.Name).Value = Left(Me.Controls(Screen.ActiveControl.Name).Value, Len(Me.Controls(Screen.ActiveControl.Name)) - 1)
End Sub
 
Hello Latex88, Welcome to AWF.. :)

Well the problem is because the Left() function does not take in Negative numbers as the secondary arguments.. If you walk through the code properly, the first line.. Screen.PreviousControl.SetFocus (the text box), then the SelStart and SelLength determines the position of the selected text and the number of characters respectively. So if the text field is completely empty (i.e. all characters have been 'deleted') then the Len() would return a 0, thus you will be performing the arithmetic 0-1, which will give -1; that cannot be handled by the compiler.. Simple solution is to exit the sub when the length of the text box control is 0..
Code:
Private Sub Key_Backspace_Click()
[COLOR=Blue]On Error GoTo errHandler[/COLOR]
    Screen.PreviousControl.SetFocus
    Me.Controls(Screen.ActiveControl.Name).SelStart = Nz(Len(Me.Controls(Screen.ActiveControl.Name)), 0)
    Me.Controls(Screen.ActiveControl.Name).SelLength = 0
    Me.Controls(Screen.ActiveControl.Name).Value = Left(Me.Controls(Screen.ActiveControl.Name).Value, Len(Me.Controls(Screen.ActiveControl.Name)) - 1)
[COLOR=Blue]exitOnErr:
    Exit Sub
errHandler:
    If Err.Number <> 5 Then Call MsgBox("Something went wrong, hope the following helps, " & vbCrLf & vbCrLf & Err.Number & " : " & Err.Description, vbCritical)
    Resume exitOnErr[/COLOR]
End Sub
Have highlighted the changes I made to your code..
Post back if you have trouble or if you do not understand something..
 

Users who are viewing this thread

Back
Top Bottom