Befor Update Len() VBA Not Working (1 Viewer)

xyba

Registered User.
Local time
Today, 14:50
Joined
Jan 28, 2016
Messages
189
Hi

Can anyone tell me why I may be getting a runtime error when executing this code (the code in red is what's causing the error apparently):

Code:
Private Sub Pwdtxt0_BeforeUpdate(Cancel As Integer)
If Len(Pwdtxt0) < 8 Then
    MsgBox "Please check your password and try again.  Passwords must be more than 8 characters!"
[COLOR="Red"]      Me.Pwdtxt0 = Null
      Me.Pwdtxt = Null
        Me.Pwdtxt0.SetFocus[/COLOR]

End If
End Sub

I have the below similar code which works perfectly on another control:

Code:
Private Sub Pwdtxt_AfterUpdate()
If Me.Pwdtxt.Value <> Me.Pwdtxt0.Value Then
      MsgBox "Passwords Don't Match", vbOKOnly
      DoCmd.RunCommand acCmdUndo
      Me.Pwdtxt0 = Null
      Me.Pwdtxt = Null
        Me.Pwdtxt0.SetFocus
Else
 

theDBguy

I’m here to help
Staff member
Local time
Today, 06:50
Joined
Oct 29, 2018
Messages
21,477
Hi. What was the error description?


Edit: Nevermind, I see the problem. You can't modify the same control in its BeforeUpdate event (it's like an infinite loop).
 

moke123

AWF VIP
Local time
Today, 09:50
Joined
Jan 11, 2013
Messages
3,921
Shouldn't you be invoking the cancel argument?
Code:
If Len(Pwdtxt0) < 8 Then
Cancel = true
...
 

Pat Hartman

Super Moderator
Staff member
Local time
Today, 09:50
Joined
Feb 19, 2002
Messages
43,302
The code that worked "correctly" is actually in the WRONG event. Validation code belongs in the "Before" events. Then you cancel the update.
Code:
Private Sub Pwdtxt0_BeforeUpdate(Cancel As Integer)
If Len(Pwdtxt0) < 8 Then
    MsgBox "Please check your password and try again.  Passwords must be more than 8 characters!"
        Cancel = True
        Me.Pwdtxt0.SetFocus
        Me.Pwdtxt0.Undo
        Me.Pwdtxt.Undo

End If
End Sub

Personally, I almost never use undo to erase what the user typed because I just get p***** off when someone does that to me. The only time I do use undo is if the user is not allowed to change anything at all - ever. Otherwise, I leave what he typed so he can see the error. An exception could be made for passwords but unless you are really plagued with hackers and leaving the wrong value will actually help them, I still would leave what the user typed.
 

moke123

AWF VIP
Local time
Today, 09:50
Joined
Jan 11, 2013
Messages
3,921
Agree with Pat. I like to see what I typed wrong so I dont repeat it.

Code:
        Me.Pwdtxt0.SetFocus
        Me.Pwdtxt0.SelStart = 0
        Me.Pwdtxt0.SelLength = len(me.Pwdtxt0)
This will select the text so you can see it and then replaces it as you start to type.
 

Users who are viewing this thread

Top Bottom