更新时间:2023-02-13 16:17:31
您为什么不使用确定"按钮来完成操作?
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.