如何根据需要将焦点放在文本框上 [英] How to put focus to textbox as needed

查看:19
本文介绍了如何根据需要将焦点放在文本框上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用户窗体上有一个文本框.如果用户未能在此文本框中输入任何内容,我需要捕获它以强制输入.我可以很容易地做到这一点,但是在通知用户他们需要输入之后,我希望焦点返回到文本框.现在,它不这样做.这是我的代码:

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

此代码工作正常,如果文本框留空,则会弹出消息框.清除消息框后,如果我再次立即回车,消息框再次出现,提示焦点在文本框上.但是,如果我尝试输入一个字符(例如数字1"),文本框中不会出现任何内容.

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!

推荐答案

您为什么不使用确定"按钮来完成操作?

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.

这篇关于如何根据需要将焦点放在文本框上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆