如何在文本框中保持 setfocus - vba excel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20300970/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:45:12  来源:igfitidea点击:

how to keep setfocus in textbox - vba excel

excelvbaexcel-vbasetfocus

提问by Tomz

I'm new in VBA, first I have a userform, textbox1and a commandbutton1. I have problem when I enter or press Tabin textbox1, I want textbox1 still in setfocusbut it clicked commandbutton1.

我是 VBA 新手,首先我有一个userform,textbox1commandbutton1. 我有问题,当我进入或按Tabtextbox1,我在想TextBox1中仍setfocus,但它点击commandbutton1

I have code below:

我有以下代码:

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
    If KeyCode = 13 Then
        TextBox1.SetFocus
    End If
End Sub

and what's VBA code to close userform1 when I press "F4" on keyboard? thank you...

当我在键盘上按“F4”时关闭 userform1 的 VBA 代码是什么?谢谢你...

回答by Siddharth Rout

Change you code from

更改您的代码

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
    If KeyCode = 13 Then
        TextBox1.SetFocus
    End If
End Sub

to

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
    '~~> 13 is for Enter, 9 is for Tab
    If KeyCode = 13 Or KeyCode = 9 Then
        KeyCode = 0
    End If
End Sub

and what's VBA code to close userform1 when I press "F4" on keyboard

当我在键盘上按“F4”时关闭 userform1 的 VBA 代码是什么

See THIS. This thread is for Esckey. Change it for F4

看到这个。这个线程是Esc关键。改变它F4

LOL. It is one of your threads.

哈哈。它是您的主题之一。

回答by Steve Rindsberg

Depending on what you need to do, you might not need any code; try setting the text box's TabKeyBehavior property to True. If you do that, the Tab keystroke gets entered as text rather than moving focus to the next control on the form.

根据您需要做什么,您可能不需要任何代码;尝试将文本框的 TabKeyBehavior 属性设置为 True。如果这样做,Tab 键击将作为文本输入,而不是将焦点移到窗体上的下一个控件。

You can do the same thing with the text control's EnterKeyBehavior property.

您可以使用文本控件的 EnterKeyBehavior 属性执行相同的操作。