按下回车键时如何防止光标移动到下一个文本框?

How to prevent cursor from moving to next textbox when Enter key is pressed?

我想防止当文本框为空并按下 Enter 键时光标移动到下一个文本框。假设我有两个文本框,Textbox1 和 Textbox2,我想要的是除非我在 Textbox1 中输入任何内容,否则当按下回车键时,它不应该允许将光标从 Textbox1 移动到 Textbox2。但它应该允许使用鼠标或箭头键手动移动光标。希望它能解释一切。 我尝试关注,

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

    If Trim(Me.txtCode) = "" And KeyCode = 13 Then
        Me.txtCode.SetFocus
    End If

End Sub

但不好

你很接近。请尝试以下操作:

Private Sub txtCode_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
   If Trim(Me.txtCode) = "" And KeyCode = 13 Then
       KeyCode = 0
   End If
End Sub

将 KeyCode 设置为 0 可有效取消击键。