PDA

View Full Version : Solved: Question about focus



lucas
07-31-2004, 10:19 AM
I found a script at the Ozgrid website that allows you to add data from a textbox to col A by keyevent(hitting enter). I am trying to figure out how to reset the focus to the textbox after the enter key is hit. Below is my latest failed attempt. Any leads would be appreciated. I was thinking that the on change event would be the time to reset the focus but I am obviously on the wrong track.

Private Sub TextBox1_Change()
TextBox1.SetFocus
End Sub

The KeyDown Code:

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
If KeyCode = 13 Then
Sheet1.Range("A65536").End(xlUp).Offset(1, 0) = TextBox1
TextBox1 = vbNullString
End If
End Sub



I have looked at all of the properties and read the help file on focus but can't seem to get this to work for me. Got to get that reference book from Mr. Excel!

Richie(UK)
07-31-2004, 02:16 PM
Hi Lucas,

This was a weird one. Eventually got it to work with the following:Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
If KeyCode = 13 Then
KeyCode = 0
Sheet1.Range("A65536").End(xlUp).Offset(1, 0) = Me.TextBox1.Value
Me.TextBox1 = vbNullString
Me.TextBox1.SetFocus
End If

End SubHTH

lucas
07-31-2004, 04:32 PM
Thanks for your expertise. I had tried:

Sheet1.Range("A65536").End(xlUp).Offset(1, 0) = TextBox1
TextBox1 = vbNullString
TextBox1.SetFocus

and even tried setting the setfocus to boolian true but I just couldn't figure it out. Thanks again, it works great. Was only wondering why you set the keycode to 0 after the If statement...Problem solved!

jamescol
07-31-2004, 05:02 PM
Hi Lucas,
The default behavior of pressing Enter in a textbox control is to set the focus to the next control in the tab order. You can control this behavior by setting the textbox control's "EnterKeyBehavior" property to False, but only when the "MultiLine" property is True.

A workaround for retaining focus in the textbox without setting the "MultiLine" property to True is to set KeyCode = 0. This has the effect of trapping the Enter keycode before it is returned to the event, thus preventing the focus from moving to the next control.

Cheers,
James

lucas
07-31-2004, 05:21 PM
James,

I understand the workaround now that you have explained about:

"trapping the Enter keycode before it is returned to the event, thus preventing the focus from moving to the next control."

It makes more sense now and explains why I(a novice)wasn't able to figure it out. Sure helps to be able to have your questions answered, thanks James and Richie for your help. The form is not all that important but the understanding is.