Enter key behavior in a ComboBox on a form
Posted on 2006-04-27
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
In the KeyDown event I have:
Private Sub ITEM_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyReturn Then
EnterPressed = True
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
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.