vba 按下回车键后继续关注文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6685661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Keep focus on textbox after pressing enter
提问by rubenploneda
How can I keep the focus in a textbox after pressing enter in a VBA form?
在 VBA 表单中按 Enter 后,如何将焦点保持在文本框中?
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?
当我单击“添加”按钮时,它会将文本添加到列表框并将焦点返回到文本框,但是当我按下 Enter 键时它不会,即使它使用相同的代码也是如此。有什么建议吗?
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.
我尝试了多种方法,但无法将焦点返回到文本框。按回车键后,焦点转到 TabIndex 中的下一个。
采纳答案by Oneide
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.
在我的脑海中:尝试将 KeyCode 设置为 0。另外,使用 KeyCodeConstants 类(来自 Core 库)来确定 Enter 键的值。
Like this:
像这样:
If KeyCode = KeyCodeConstants.vbKeyReturn Then
CmdAddOtherAsset_Click
KeyCode = 0
End If
Remove the line you're trying to set the focus on the other sub (TxtOtherAsset.SetFocus
).
删除您试图将焦点设置在另一个子 ( TxtOtherAsset.SetFocus
) 上的行。
Hope it works for you. I did not test it.
希望对你有效。我没有测试它。
回答by TheOtherTimDuncan
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.
您是否使用 Enter 键作为触发器来捕捉对文本框的更改?如果是这种情况,请尝试使用 After Update 事件。另外,看看 On Exit 事件。当我查看时,我注意到它有一个 Cancel 参数。如果您仍然想在 Key Down 事件中捕获 Enter 键,您可能可以使用 On Exit 事件来防止离开文本框。当然,这可能意味着您永久卡住了,可能需要设置允许退出的方法。