How to put focus to textbox as needed

AndroidDev picture AndroidDev · Jun 6, 2012 · Viewed 94.1k times · Source

I have a textbox on a userform. If the user fails to enter anything in this textbox, I need to trap that to force an entry. I can do this easily enough, but after notifying the user tht they need to make an entry, I want the focus to return to the textbox. Right now, it doesn't do that. Here is my code:

Private Sub txtAnswer_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

Select Case KeyCode
    Case 13:
        If Me.txtAnswer.Value = "" Then
            temp = MsgBox("You need to enter an answer!", vbCritical + vbOKOnly, "No Answer Found!")
            Me.txtAnswer.SetFocus
        Else
            recordAnswer
        End If
    End Select

End Sub

This code works fine in that the message box pops up if the textbox is left blank. After clearing the message box, if I hit enter immediately again, the message box reappears, suggesting that the focus is on the textbox. However, if I try to enter a character (like the number '1' for example) nothing appears in the textbox.

Can anybody suggest how I can get the focus back on this textbox in a way that will allow the user to enter data? Thank you!

Answer

Reafidy picture Reafidy · Jun 6, 2012

Why are you not using an 'ok' button to complete the action?

You should not bother users with messages while they are typing in a form. Do it at the end.

Private Sub OK_Click()

    '// Validate form
    If txtAnswer.Text = vbNullString Then
        MsgBox "You need to enter an answer!", vbExclamation, "No Answer Found!"
        txtAnswer.SetFocus
        Exit Sub
    End If

    '// You have reached here so form is correct carry on
    recordAnswer

End Sub

If you really want to use the behaviour you asked for then try this:

Private Sub txtAnswer_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

    Select Case KeyCode
    Case 13:
        If Me.txtAnswer.Value = "" Then
            temp = MsgBox("You need to enter an answer!", vbCritical + vbOKOnly, "No Answer Found!")              
            KeyCode = 0
        Else
            recordAnswer
        End If
    End Select

End Sub

The problem is that in your code you are setting focus but the enter key is firing afterwards. You don't need to set focus because the textbox already has the focus you just need to cancel the enter key.