Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Lost/Got Focus

Status
Not open for further replies.

PJHAction

Technical User
Aug 22, 2003
29
US
I have a Form, lets say it is Form1, on it is SubForm2 and SubForm3. I am trying to tab key from SubForm2/Field6 to SubForm3/Field1. How do I get the Focus option to work.

Pete
 
On Lost Focus or Exit of the last field in the main form setfocus to the first field on the subform.
 
I know I must use SetFocus, but I cannot get any code to work. Looking for an example on what should be typed in for code.

Pete
 
Normally this would be done in the KeyPress event. You capture the code of the key that was pressed (TAB is vbkeytab which = 9), then do whetever you need if that key is pressed.

You can't reliably use LostFocus event, since the field you're tabbing from has not lost focus until some other control has already received the focus. That means you're already on some other control. You can't use the Exit event either, because that happens after the LostFocus.

Private Sub Field6_KeyPress(KeyAscii As Integer)
If KeyAscii = vbKeyTab Then
Forms("SubForm3").Field1.SetFocus
End If
End Sub

This will set the focus after normal processing of Field6. If you want to ignore the contents of Field6 and go straight to the SetFocus field, add KeyAscii = 0 before the End If. That will reset the key and pretend nothing was entered (but your focus has already been set so it will still happen).

 
Hi jigjag,

Sorry, I disagree with you, code should read:

Private Sub Field6_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyTab Or KeyCode = vbKeyReturn Then
KeyCode = 0
Forms!Form1!SubForm3.SetFocus
Forms!Form1!SubForm3.Form!Field1.SetFocus
End If
End Sub

The KeyPreview property of SubForm2 must be set to Yes. Delete "Or KeyCode = vbKeyReturn" if you don't want to use the Enter key as well as the Tab key.

Bill
 
Bill, you're correct about setting the focus twice, which you need to do when using subforms.

You can use either KeyPress or KeyDown for this. KeyDown is usually used when you need to know "shift" key codes, KeyPress otherwise. For the Tab key, normally you don't care what other key was pressed with Tab, just that the Tab was pressed.
 
Hi jiqjaq,

I completely agree with that. But I always use the KeyDown event because it can be added to, that's all. My standard answer.

Keep up your good work.

Best Regards

Bill
 
Great responses, will give it a try and respond with my results.

Pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top