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

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

问题描述

我在用户表单上有一个文本框.如果用户无法在此文本框中输入任何内容,我需要对其进行陷阱以强制输入.我可以很容易地做到这一点,但是在通知用户他们需要输入之后,我希望焦点返回到文本框.目前,它没有这样做.这是我的代码:

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

此代码可以正常工作,因为如果文本框为空,则消息框会弹出.清除消息框后,如果我再次立即按下Enter键,则会再次出现该消息框,表明焦点位于文本框上.但是,如果我尝试输入字符(例如数字'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

问题在于,您在代码中设置了焦点,但之后又按下了Enter键.您不需要设置焦点,因为文本框已经具有焦点,您只需要取消Enter键即可.

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天全站免登陆