Enter key behavior in a ComboBox on a form

Posted on 2006-04-27
Medium Priority
Last Modified: 2008-01-09
I have a combo box in an Access 2003 form in which I would like to be able to  enter multiple lines.  Text boxes have a property called “Enter key behavior” which can be set to “New line in field”, which is what I want, but combo boxes don’t have that property available.

First off, if I’m missing something simple please let me know.

After trying a lot of different things I came up with a solution that “sort of” works.

In the VBA code on the form I added a variable “EnterPressed”:

      Option Compare Database
      Dim EnterPressed As Boolean ‘ set EnterPressed as a global variable

In the ComboBox On Enter Event I have (the control name is “Item”):

      Private Sub Item_Enter()

      EnterPressed = False

      End Sub

In the KeyDown event I have:

      Private Sub ITEM_KeyDown(KeyCode As Integer, Shift As Integer)
      If KeyCode = vbKeyReturn Then
                EnterPressed = True
      End If
      End Sub

And in the Exit event I have:

If EnterPressed Then

   Me.Item = Me.Item & vbCrLf    ' Add a new line to the field
   DoCmd.GoToControl "Item"       ' Move the focus back to the field
   ' Move cursor to the position 1 more than the length of the field
   Me.Item.SelStart = Len(Me.Item) +1                                                      
   ' Make the number of characters  actually  selected = zero
   Me.Item.SelLength = 0                                                                                
   EnterPressed = False
End If

The idea is that when a user enters the field a flag is set that indicates they have not hit the Enter key yet.  If they don’t, and Tab or Mouse out of the field, nothing unusual happens.  If they do hit Enter, a flag is set, and when the field is exited a cr/lf is added to the field, focus is set back to the field, the curser is put at the beginning of the new line, and they keep typing.

This works, EXCEPT if there is already a cr/lf at the end of the string when the On Exit event runs.  This happens if the user tries to double space by hitting Enter twice, or had hit Enter once before but did not enter any additional text before leaving the field.

If these cases, the code seems to run all the way through correctly, the cr/lf is added, but the cursor ends up at the beginning of the field and the entire field is selected.

If anyone can help it would be great.  If there is a completely different approach that would be great also.

Question by:misgci
  • 4
  • 3
  • 2
  • +2
LVL 54

Assisted Solution

nico5038 earned 150 total points
ID: 16557675
Just pressing CTRL+Enter will give you the next line as needed.
Can you live with that ?


Expert Comment

ID: 16557726

Combo box in Access was NOT build for this purpose, you'll end up no where, retrofitting this kind of multiline functionality into combo box artificially.

So, it's better for you, please donot waste your precious time in that. If you want to get multline input, use appropiate input control like a textbox etc.

Syed Nabeel.

Author Comment

ID: 16558455

I can live with CTRK+Enter, it's what I usually do myself, I was just trying to make it easier for the people using the form.
They may just have to get used to it.


But the fun of doing stuff like this is to make an application do more than it was intended to do!
I've got it so close to working I have to give it at least a little more effort.

The reason I want a combo box is that this is an item description on a purchase order.  The combo box looks up items previously ordered from the selected vendor.  Since these descriptions are often repeated, and are sometimes long and complicated, with item codes, style numbers, etc., it is much easier and more efficient if the user can pick from a list once they put in the first few characters.

So, I'm going to hold out a little more, and keep plugging away at it myself and hopefully have a solution.

Thanks for your comment.

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

LVL 58

Accepted Solution

harfang earned 600 total points
ID: 16558876

To change the behavior of the Enter key, use the KeyDown event. To suppress further interpretation of the keypress, you simply set KeyCode to 0.

Private Sub cboNotes_KeyDown(KeyCode As Integer, Shift As Integer)

    Dim intPos As Integer

    If KeyCode = vbKeyReturn _
    And (Shift = 0 Or Shift = acCtrlMask) Then
        KeyCode = 0   ' we handle thar ourselves!
        intPos = cboNotes.SelStart
        cboNotes.SelText = vbCrLf
        cboNotes.SelStart = intPos + Len(vbCrLf)
    End If

End Sub

However, Syed is absolutely right: you should not do that. You are creating a non-standard interface by obfuscating the normal expected behaviour of a control. Also consider that:
- you loose the scroll-bar (useful if the memo field is long)
- the combo returns only 255 characters (you will truncate longer previous comments)
- the users can easily loose data by clicking accidentally
- you cannot warn the user that s/he is overwriting data

All it all, cute but a rather bad idea.

Instead, create another unbound combo right next to your text box, with these properties (I tested on the table Employees, field Notes):

Row Source: Select EmployeeID, Notes From Employees Where Notes Is Not Null;
Column Count: 2
Column Widths: 0.125"
List Width: 2.5"
Width: 0.1667"   (same as height)
Tab Stop: No
Controltip Text: Copy notes from another Employee

Use events much like the following:

Private Sub cboCopyFromPrevious_AfterUpdate()

    With Me.RecordsetClone
        .FindFirst "EmployeeID = " & Me.cboCopyFromPrevious
        If Not .NoMatch Then
            If Not IsNull(Me.txtNotes) Then
                If MsgBox("Overwrite?" & vbCrLf & vbCrLf & Me.txtNotes _
                    , vbQuestion + vbOKCancel _
                    , "Warning" _
                    ) = vbOK Then Me.txtNotes = !Notes
                Me.txtNotes = !Notes
            End If
        End If
    End With
    Me.cboCopyFromPrevious = Null

End Sub

Private Sub cboCopyFromPrevious_Enter()
End Sub

You now have an additional tool, with a clear meaning, tooltip help, its own paragraph in the user manual, etc.

Have fun!
LVL 74

Expert Comment

by:Jeffrey Coachman
ID: 16628975
<But the fun of doing stuff like this is to make an application do more than it was intended to do!>
Not exactly.
Remember the old saying:
Just because something *can* be done, doesn't mean it *should* be done. (even if it is fun)

Like the two previous posters say, what you are asking is Non-standard and counter-intuitive. If your user acclimate themselves to this, they will expect it in other windows base programs, and it won't work!
No combobox, in any other program, works in the way you are describing.
(check the Microsoft help file.)

If you are simply trying to stop users from accidentally pressing Enter and leaving a field, simply turn this functionality off in the options menu:
Tools--> Options-->Keyboard
Change: Move After Enter
To: Don't move

Nico5038 is correct in providing you with a workaround.
harfang is also to be commended for his solution.
(As anyone will tell you,: "The customer is always right")
And they have, in fact, answered your original question.

But just humor me:
What are you ultimately trying to accomplish?
Or, more specifically, what user error are you trying to avoid?
Or am I missing the point altogether?


Author Comment

ID: 16630413
It's really not that complicated - when users are filling in the description of a line-item on a purchase order, the control on the form is a combo box which looks up previously purchased items from the current vendor.  It is faster and more accurate for the users to be able to pick from a list since many items are repeat orders.

This works fine.  Before it was changed to a combo box, it was a text box.  When it was a text box users could press enter to get a new line which allowed each line-item description to be two or three lines, which makes the purchase orders easier to read.

With it being a combo box, as nico5038 said, the same result could be had by pressing CTRL+Enter, but users are already in the habit of just hitting enter to create a new line.  When doing so they end up in the next field, which is numeric, and end up with errors.  I could change the move after enter option, but that becomes universal for all Access applications, which may not be the desired result.

I was looking for a way to programmatically change an "Enter" to a "CTRL+Enter", which would give  users the same keyboarding method they had before, with the added benefit of having a drop down box.  I tried several ways to do this but nothing worked the way I wanted.

I haven't been able work on this for a few days, but I am probably going to take a look at the approach suggested by harfang and use a separate unbound combo box for a lookup list, but in the meantime, the users are simply using CTRL+Enter, which gives them the results they want.

LVL 58

Expert Comment

ID: 16630658

In the top of my answer, I also provided a solution for that: have the enter key create a new line in a combo box. It's the first function, just copy-paste and adjust for your combo's name.
[I'm still recomending you change it to an external combo, though ;) ]

Good luck!
LVL 74

Expert Comment

by:Jeffrey Coachman
ID: 16630858

Thanks for the info.

Author Comment

ID: 16630958
Well, when I tried that as is (changing the combo box name) it didn't work.  You could see the cursor momentarily jump to a new line, but then it would go right back to the end of the first line.  The length of the string in the combo box did not change.

If I modify it as follows:

Private Sub cboNotes_KeyDown(KeyCode As Integer, Shift As Integer)

    Dim intPos As Integer

    If KeyCode = vbKeyReturn _
    And (Shift = 0 Or Shift = acCtrlMask) Then
        KeyCode = 0   ' we handle thar ourselves!
        intPos = cboNotes.SelStart
        'cboNotes.SelText = vbCrLf
        cboNotes=cboNotes & vbCrLf
        cboNotes.SelStart = intPos + Len(vbCrLf)
    End If

End Sub

it works, but only if the Enter key is hit once.  If it is hit twice, as if the user wanted to skip a line, it seems to strip the second CrLf off, in the same manor as the original code.

Access apparently is just not going to cooperate with this, so the second approach will be the way to go.
LVL 58

Expert Comment

ID: 16631573
It's probably best, yes. Let's not continue that path. I did test it before  posting, however, and it worked for me. And incidentally, this line does not work, you need to use the .Text property:

      cboNotes.Text = cboNotes.Text & vbCrLf

But as I said, it's best to just drop it.

Author Comment

ID: 16633704
OK well I appreciate all the comments and especially the advice from harfang.
I'll go with the unbound combo box and stop trying to twist Access to do something it shouldn't.

Thanks again for your time and helpfulness.


Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Code that checks the QuickBooks schema table for non-updateable fields and then disables those controls on a form so users don't try to update them.
Windows Explorer let you handle zip folders nearly as any other folder: Copy, move, change, and delete, etc. In VBA you can also handle normal files and folders, but zip folders takes a little more - and that you'll find here.
Basics of query design. Shows you how to construct a simple query by adding tables, perform joins, defining output columns, perform sorting, and apply criteria.
With Microsoft Access, learn how to start a database in different ways and produce different start-up actions allowing you to use a single database to perform multiple tasks. Specify a start-up form through options: Specify an Autoexec macro: Us…

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question