8

I have a combobox on a form and I'm trying to programmatically select one of the items in the combobox after I've run my SQL query on the access database. I use the following code to iterate over the items and set the selected item:

'Make the appropriate location appear in the combobox
For i = 0 To cboLocations.ListCount - 1
  If Me.cboLocations.Column(0, i) = locindex Then
    Debug.Print "locindex: " & locindex & vbCrLf & " Me.cboLocations.Column(0, i):" & Me.cboLocations.Column(0, i)
    Me.cboLocations.SetFocus
    Me.cboLocations.ListIndex = i '<<< error 2115
    Exit For
  End If
Next i

As indicated, I keep getting error 2115: The macro or function set to the BeforeUpdate or ValidationRule property for this field is preventing Access from saving the data in the field.

Neither of the properties for this combobox indicated in the error message is set to anything. So I'm stuck. Please advise.

HansUp
  • 95,961
  • 11
  • 77
  • 135
Alan
  • 822
  • 1
  • 16
  • 39

2 Answers2

2

programmatically select one of the items in the combobox

The way I've always done that is to assign something to the combo's Value like this ...

Me.MyCombo.Value = "target text"

Value comes from the Bound Column of the combo's selected row. (You can find Bound Column on the Data tab of the combo's property sheet.) Conversely, assigning "target text" to Value selects the matching row.

In your situation, I think you're trying to select the combo row which contains the same text as your locindex variable. And if that is true, then I think all you need is this ...

Me.cboLocations.Value = locindex

As far as when you do that, neither Before Update nor Validation Rule seems like the right choice to me. I suggest you do it from whatever code you're using to run your "SQL query on the database", immediately after the query.

HansUp
  • 95,961
  • 11
  • 77
  • 135
  • Thank you. This was actually something I could work with and was useful. I wound up replacing Me.cboLocations.ListIndex = i with Me.cboLocations.Value = Me.cboLocations.Column(1, i) as there are two columns in the combobox and also added Me.cboLocations.Selected(i) = True to make sure the specific item was selected in the list. – Alan Oct 12 '15 at 23:41
1

You are probably colliding with the BeforeUpdate event.

Try using AfterUpdate.

Gustav
  • 53,498
  • 7
  • 29
  • 55