将焦点设置在用户窗体文本框上,以从另一个文本框制表 [英] Set focus on UserForm Textbox on tabbing from another Textbox
问题描述
我在Excel中有一个用户窗体.它具有6个文本框,它们是用户窗体上唯一将TabStop设置为True的控件.
I have a Userform in Excel. It has 6 Textboxes, they are the only controls on the Userform with TabStop set to True.
我可以选择并在文本框中移动.我无法让 SetFocus
处理在文本框之间移动时触发的事件.我可以使用 Userform16.Textbox1.Setfocus
将CommandButton放在用户窗体上,并且按预期的方式将焦点移至Textbox1.
I can tab and move through the textboxes. I cannot get SetFocus
to work on Events fired when moving between the Textboxes. I can put a CommandButton on the userform with Userform16.Textbox1.Setfocus
and it works as expected to move the focus to Textbox1.
我设置了一个简单的测试事件(请参见下文),以在输入Textbox2时将文本框焦点移回TextBox1.当我跳出TextBox1时,它将焦点移至Textbox3.
I set up a simple test event (see below) to move the textbox focus back up to TextBox1 when Textbox2 is entered. It moves focus to Textbox3 when I tab out of TextBox1.
Private Sub TextBox2_Enter()
Cancel = True
UserForm16.TextBox1.SetFocus
End Sub
通过在上面放置一个 Stop
,我可以看到该事件正在按预期触发,但是它不允许我控制下一个控件的焦点.
By putting a Stop
in the above, I can see that the event is firing as expected, but it will not allow me to control the focus the next control.
无论子程序中是否使用 Cancel = True
语句,我都能得到相同的结果.
I get the same results with or without the Cancel = True
statement in the sub.
推荐答案
我设置了一个简单的测试事件(请参见下文),以在输入Textbox2时将文本框焦点移回TextBox1,而当我从TextBox1中跳出时,实际上会将焦点移至Textbox3.
I set up a simple test event (see below) to move the textbox focus back up to TextBox1 when Textbox2 is entered, it actually moves focus to Textbox3 when I tab out of TextBox1.
您不能在 _Enter()
事件中将焦点设置到另一个控件上.如果您尝试执行此操作,则该代码将把焦点转移到具有下一个 TabIndex
You can't set focus to another control in the _Enter()
event. If you try to then the code will move focus to control which has the next TabIndex
例如
假设您有5个文本框,其中包含以下 TabIndex
Let's say you have 5 textboxes with the following TabIndex
TextBox1 (TabIndex 0)
TextBox2 (TabIndex 1)
TextBox3 (TabIndex 3)
TextBox4 (TabIndex 4)
TextBox5 (TabIndex 2)
现在,如果您有此代码
Private Sub TextBox2_Enter()
TextBox3.SetFocus
End Sub
当您从 TextBox1
中按 TAB 时,焦点将移至 TextBox5
(而不是 TextBox3
)因为它具有下一个 TabIndex
.
The moment you press TAB from TextBox1
, the focus will move to TextBox5
(and not TextBox3
) as it has the next TabIndex
.
也 Cancel = True
不会有任何效果,因为它不是 _Enter()
的参数,就像 Private Sub TextBox2_Exit(ByVal Cancel作为MSForms.ReturnBoolean)
Also Cancel = True
will not have any effect because it is not an argument of _Enter()
like it is of say Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
修改
顺便说一句,在您的方案中,焦点唯一返回到 Textbox1
的情况是表单中只有两个 TextBoxes
.
BTW, the only time the focus will come back to Textbox1
in your scenario is when there are only two TextBoxes
in the form.
这篇关于将焦点设置在用户窗体文本框上,以从另一个文本框制表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!