How to code Enter key to run a command assigned to a button

G

Guest

Hi there,

I'm trying to code the Enter key so that when the user presses Enter, the
form's "submit" command is run.

I have a search form where the user can type a search string and then click
"Search" to submit the search criteria. What I would like to do is also
allocate the Enter key to run the Search command. I am using MS Access 2002.

Any ideas?

Thanks in anticipation.
 
D

Douglas J. Steele

Set the form's KeyPreview property to Yes. In the form's KeyDown event, and
put logic to invoke the Search code when KeyCode is 13.
 
G

Guest

Hi Doug,

That works great, thanks
However, I'm also checking to see whether they typed anything into the
search box and if my user presses Enter before the focus changes the code
thinks they didn't type anything. Any ideas for that?

Thanks
 
D

Douglas J. Steele

So do you only really care about them hitting Enter in that text box, or
when focus is anywhere else on the form?

To ensure you've got what they've just typed in the box, call the search
logic from the text box's AfterUpdate event.

While you could change the code in the form's KeyDown event to something
like:

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
If Len(Me.MyTextbox & vbNullString) > 0 Then
' Call your search logic
End If
End If
End Sub

that won't work if they've changed what's in MyTextbox: it'll remember what
used to be there until the AfterUpdate event fires. You could try something
like:

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
Static strLastValue As String

If KeyCode = 13 Then
If Len(Me.MyTextbox & vbNullString) > 0 Then
If strLastValue <> Me.MyTextBox Then
strLastValue = Me.MyTextBox
' Call your search logic
End If
End If
End If
End Sub
 
G

Guest

Hi Doug,

I've just sorted it - but thank you!

I told the Form_KeyDown sub to set the focus to the command button that the
Enter key will emulate and then call the subroutine.

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
cmdSearch.SetFocus
cmdSearch_Click
End If
End Sub

Seems to work ... if not I'll be back!

Cheers again
Amanda
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top