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!

Control Question

Status
Not open for further replies.

avagodro

Technical User
Aug 12, 2005
83
US
I am trying to add an event to a text box that if you press the enter key, it would run the code for the OK button. The following code has been tried.

Private Sub YourControl_KeyPress(KeyAscii As Integer)
If KeyCode = vbKeyEnter Then
Call cmdOk_Click
End If
End Sub

At first, KeyCode generated a Compile Error, that the variable was not define. I changed it to KeyAscii, then the code stopped at vbKeyEnter and got an error as well. I changed that to vbKeyReturn and I get no errors, but nothing happens either.

Any thoughts?
 
Should it not be KeyAscii rather than KeyCode?

Have fun! :eek:)

Alex Middleton
 
I tried KeyCode and I received a Compile Error: Variable not defined.
 
The variable passed into the sub is KeyAscii.

Have fun! :eek:)

Alex Middleton
 
The very amusing thing with these events (keydown/keypress), is that when you fire off a key that alters the focus of controls (like tab or enter), that key is not received by this controls keypress event - but the keypress event of the next control in the key sequence.

This means that to reliably trap the enter key for the current control, you must use the keydown event. There is no constant called vbkeyenter, but the character returned by hitting the enter key, is vbKeyReturn - and in the keydown event you compare this key is returned through the KeyCode parameter.

Roy-Vidar
 
Thanks. What I ended up having to do is:

Private Sub txt1_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyReturn Then
DoCmd.GoToControl "cmdOk"
Call cmdOk_Click
End If

End Sub


without the DoCmd.GotoControl "cmdOk" I would receive an error "Invalid use of Null".
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top