VBA Tab Tab Adds Actual Tab Value to Text Box Instead of Going to Next Control

I have a VBA form (in Excel, if that matters) that contains text fields.

In three cases, I found that I pressed the Tab key to go to the next control, but instead the actual TAB was placed in the text box.

The form usually acts as it should, but it bothers me that this gremlin appears sporadically.

He appeared in Office 2003, as well as Office 2007 on two different computers.

Has anyone else encountered this problem, and if so, how did you fix it?

+6
vba excel-vba
source share
5 answers

I was able to reproduce the problem in 100% of cases by running Excel, immediately pulling up the form and holding the tab key.

If I change any code in the form at all and save the book, the problem disappears. I am going to write this down to a fluke compilation error in VBA.

+2
source share

I created a form with three text fields. I introduced the characters and for a while laid a tab on the next one without repeating your problem.

The only way to get a tab in the text box is to enter Ctrl + Tab. It may be awkward, but the backspace removes it, so this is not a serious problem. Is it possible that you accidentally pressed Ctrl at the same time?

Sometimes I find that if I miss a key, the cursor will move to another place on the screen. I am not quite sure what I mean by "fallacy"; This seems to be due to the simultaneous pressing of two keys. This is apparently a feature of modern keyboards and how they detect which key was pressed because I ran into it on different computers. The implication is that by running the key, a control character is generated (possibly a tab or ctrl + tab).

I also tried the following, which worked and hides the problem by deleting the tab and moving on to the next control.

Private Sub TextBox1_Change() If InStr(1, TextBox1.Text, Chr(9)) <> 0 Then TextBox1.Text = Replace(TextBox1.Text, Chr(9), "") TextBox2.SetFocus End If End Sub 
+1
source share

For a quick workaround, use this code in an Exit control.

 Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean) TextBox1.Text = VBA.Replace(TextBox1.Text, VBA.Chr(9), "") End Sub 
+1
source share

Set the TabKeyBehavior property to False to get the Go To Next Field behavior.

0
source share

This may solve the problem:

 Public Sub MoveFocusToNextControl(xfrmFormName As UserForm, _ xctlCurrentControl As control) Dim xctl As control Dim lngTab As Long, lngNewTab As Long On Error Resume Next ' Move focus to the next control in the tab order lngTab = xctlCurrentControl.TabIndex + 1 For Each xctl In xfrmFormName.Controls lngNewTab = xctl.TabIndex ' An error will occur if the control does not have a TabIndex property; ' skip over those controls. If Err.Number = 0 Then If lngNewTab = lngTab Then xctl.SetFocus Exit For End If Else Err.Clear End If Next xctl Set xctl = Nothing Err.Clear End Sub 
0
source share

All Articles