PDA

View Full Version : unable to set focus



RatherBeRidi
05-25-2012, 06:48 AM
I think this should be so easy, but can't get determine why it does not work. I can't get the focus back to txtFTE after the message displays. It always jumps to the next field on the userform. I've tried moving the last two statements in the IF outside of the IF statement and reversing their order, but the focus always moves to the next field. Can some please identify my error?

Private Sub txtFTE_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Dim MyValue
MyValue = Me.txtFTE.Value
If Not IsNumeric(MyValue) Then
MsgBox "Care Manager FTE must be a number.", vbCritical, "Invalid Entry"
Me.txtFTE.Value = ""
Me.txtFTE.SetFocus
End If
End Sub

RatherBeRidi
05-25-2012, 08:31 AM
I tried something else (below) which now displays the message, and retains the focus in txtFTE. However, after clicking on the OK button of the message, it displays again. Clicking on the OK button a second time returns to the form. Any ideas why it would display twice?

Private Sub txtFTE_Change()
If Not IsNumeric(txtFTE) Then
MsgBox "Care Manager FTE must be a number.", vbCritical, "Invalid Entry"
Me.txtFTE.Value = vbNullString
End If
Me.txtFTE.SetFocus
End Sub

Rob342
05-25-2012, 01:53 PM
change
If Not IsNumeric Val(Me.txtFTE.Text) Then

Remember all form fields are always text, you need to convert them to numbers then chk the validation.

Aflatoon
05-28-2012, 12:27 AM
No you don't actually and Val() will always return a numeric value (it converts text to 0)

For the original code you would set the cancel argument to true
Private Sub txtFTE_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Dim MyValue
MyValue = Me.txtFTE.Value
If Not IsNumeric(MyValue) Then
MsgBox "Care Manager FTE must be a number.", vbCritical, "Invalid Entry"
cancel = true
End If
End Sub

mikerickson
05-28-2012, 12:48 AM
Instead of validating numeric entry after the fact, this will prevent the user from entering non-numeric values.

Private Sub TextBox2_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Dim newText As String

With TextBox2
newText = Left(.Text, .SelStart) & Chr(KeyAscii) & Mid(.Text, .SelStart + .SelLength + 1)
End With

KeyAscii = -KeyAscii * IsNumeric(newText & "0")
End Sub

Aflatoon
05-28-2012, 12:58 AM
FWIW, I've found that that confuses users more than simply validating after the fact.