I was trying to validate a phone number before proceeding and was using TextBox.SetFocus to return to the textbox in question when there was an error, but it proceeded to the next control anyway. I gave up on that and modified some code I found from Dave (which cured the SetFocus problem).
The code below gives me the msgbox no matter what. I changed the code to allow for just the 10 digit phone number, and for the () and spaces. What am I doing wrong? Is there a better way?
All I'm trying to do is verify that the user has plugged in a 10-digit phone number. If not, set focus back to the offending textbox, otherwise, format the textbox and move on.
Code
Private Sub txtPhone_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If Len(txtPhone.Text) <> 10 Or Len(txtPhone.Text) <> 14 Then
MsgBox "Error in Phone number"
Cancel = True
With txtPhone
.SelStart = 0
.SelLength = Len(.Text)
End With
Else
txtPhone.Value = Format(txtPhone.Text, "(000) 000-0000")
End If
End Sub
Display More