VBA:如何从组合框选择项 [英] VBA: How to select item from a ComboBox
问题描述
我有机会获得2010表单里面有一个组合框 cmbSubTopic
,列出两列( SubTopicID
和子话题</ code>)。该组合框绑定到包含
SubTopicID
字段。该 SubTopicID
列在组合框被隐藏,只显示了子话题</ code>。当用户从下拉相应的
SubTopicID
存储在表中选择一个子话题</ code>。我写了一些VBA code为在窗体的加载事件来查找
SubTopicID
中的表和相应的子话题</ code>选择在组合框中。我现在的code是这样的:
I have Access 2010 form which has a ComboBox cmbSubTopic
which lists two columns (SubTopicID
and SubTopic
). The combo box is bound to a field containing SubTopicID
. The SubTopicID
column in the combo box is hidden, it only shows the SubTopic
. When the user selects a SubTopic
from the drop down the corresponding SubTopicID
is stored in the table. I wrote some VBA code for the on load event of the form to look up the SubTopicID
in the table and the corresponding SubTopic
is selected in the ComboBox. My current code is something like this:
Set rsST = dbs.OpenRecordset(strSqlst)
For i = 0 To Me.cmbSubTopic.ListCount - 1
If Me.cmbSubTopic.Column(0, i) = rsST.Fields("SubTopicID").Value Then
Me.cmbSubTopic.SetFocus
Me.cmbSubTopic.Selected(i) = True
Exit For
End If
Next i
这给出了错误说:
您输入的内容不在列表中的项目
The text you entered isn't an item in the list
我也尝试过使用这样的:
I also tried using this:
Me.cmbSubTopic = Me.cmbSubTopic.Selected(i)
这个选择ComboBox中的项目,但它也写道,我不希望表的我的价值到 ID
字段。
This selects the item in the ComboBox but it also writes the value of I in to the ID
field of the table which I don't want.
推荐答案
假设组合的第一列, SubTopicID
,也是组合的绑定列属性,它是作为该列的。价值
属性。这意味着你只需要以选择匹配的组合行分配一个值。价值
。
Assuming the combo's first column, SubTopicID
, is also the combo's "bound column" property, it is used as the column's .Value
property. That means you only need to assign a value to .Value
in order to select the matching combo row.
Me.cmbSubTopic.Value = rsST.Fields("SubTopicID").Value
这方法很简单,但我不确定它是否是您的具体情况相应的解决方案。我们不知道你的 RSST
记录什么---我presumed在 SubTopicID
字段中记录的当前行是要在组合选择的值。如果我误解了这一点,我们需要找出不同的东西。
That approach is simple, but I'm uncertain whether it is the appropriate solution for your situation. We don't know anything about your rsST
recordset --- I presumed the SubTopicID
field in the recordset's current row is the value you want selected in the combo. If I misunderstood that point, we need to figure out something different.
如果该组合被绑定到字段在窗体的记录源,这个建议也将改变存储的值。如果你不希望这样,取消绑定组合---换句话说,使其的控制源代码的属性为空。
If the combo is bound to a field in the form's record source, this suggestion would also change the stored value. If you don't want that, "unbind" the combo --- in other words, make its Control Source property blank.
这篇关于VBA:如何从组合框选择项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!