按 Enter 键后将焦点保持在文本框上
在VBA窗体中按回车键后如何将焦点保持在文本框中?
此代码将文本添加到列表框,我想将焦点保持在文本框上以准备接收另一个项目。
当我单击“添加”按钮时,它将文本添加到列表框并将焦点返回到文本框,但是当我按 Enter 时,它不会,即使它使用相同的代码。有什么建议吗?
这是我的文本框代码:
Private Sub TxtOtherAsset_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
CmdAddOtherAsset_Click
End If
End Sub
这是我的按钮代码:
Private Sub CmdAddOtherAsset_Click()
If TxtOtherAsset.Text <> "" Then
ListAddedAssets.AddItem TxtOtherAsset.Text
TxtOtherAsset.Text = ""
End If
TxtOtherAsset.SetFocus
End Sub
我尝试了多种方法,但我无法将焦点返回到文本框。按 Enter 后,焦点将转到 TabIndex 中的下一个。
How can I keep the focus in a textbox after pressing enter in a VBA form?
This code adds the text to a Listbox and I want to keep the focus on the textbox to get ready to receive another item.
When I click in the button Add, it adds the text to the Listbox and returns the focus to the textbox, howerver when I press enter it doesn't, even tough it uses the same code. Any suggestion?
This is my code for the textbox:
Private Sub TxtOtherAsset_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
CmdAddOtherAsset_Click
End If
End Sub
and this is the code for my button:
Private Sub CmdAddOtherAsset_Click()
If TxtOtherAsset.Text <> "" Then
ListAddedAssets.AddItem TxtOtherAsset.Text
TxtOtherAsset.Text = ""
End If
TxtOtherAsset.SetFocus
End Sub
I've tried several ways, but I'm not able to return the focus to the textbox. After pressing enter, the focus goes to the next in the TabIndex.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的想法是:尝试将 KeyCode 设置为 0。另外,使用 KeyCodeConstants 类(来自 Core 库)来确定 Enter 键的值。
像这样:
删除您尝试将焦点设置在另一个子项目上的行(
TxtOtherAsset.SetFocus
)。希望它对你有用。我没有测试它。
From the top of my head: try setting the KeyCode to 0. Also, use the KeyCodeConstants class (from the Core library) to determine what value the Enter key is.
Like this:
Remove the line you're trying to set the focus on the other sub (
TxtOtherAsset.SetFocus
).Hope it works for you. I did not test it.
您是否使用 Enter 键作为触发器来捕获文本框的更改?如果是这种情况,请尝试更新后事件。另外,请查看 On Exit 事件。当我查看时,我注意到它有一个取消参数。如果您仍然想在 Key Down 事件中捕获 Enter 键,则可以使用 On Exit 事件来防止离开文本框。当然,这可能意味着您永久陷入困境,可能需要设置一种允许退出的方法。
Are you using the Enter key as a trigger to catch changes to the text box? If that's the case, try the After Update event instead. Also, take a look at the On Exit event. When I looked, I noticed it has a Cancel parameter. If you still want to catch the Enter key in the Key Down event, you could possibly the On Exit event to prevent leaving the text box. Of course, that probably means you're permanently stuck and may need to set up a way to allow exiting.