访问VBA:如何计算组合框的项目数?

3 ms-access vba combobox count selection

在我的中,ComboBox我已经选择了一些项目。

我想用VBA来计算它们。我本来希望找到类似以下字符串的内容,但我得到了Compile error: Argument not optional

Me.<ComboBox_name>.ItemData.Count
Run Code Online (Sandbox Code Playgroud)

我还想使用以下字符串,但它给了我0项目:

Me.<ComboBox_name>.ItemSelected.Count
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Gus*_*tav 8

如果要计算选项的话,就是:

Me!<ComboBox_name>.ListCount
Run Code Online (Sandbox Code Playgroud)

或者准确地说,如果您使用列标题:

Me!<ComboBox_name>.ListCount - Abs(Me!<ComboBox_name>.ColumnHeads)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢:-)你救了我。 (2认同)

小智 5

组合框通常用于选择或显示单个项目的选择,而列表框自然支持多个选择。

也就是说,例如,如果您将多值* 表字段链接到组合框,则您可以拥有一个包含多个选择的组合框。如果是这种情况,则值在属性中可用的唯一时间.ItemsSelected是当组合框具有焦点并被下拉时。

解决此问题的一种方法是将组合框的.Value属性分配给数组。该数组将包含选定的值。您可以通过取数组的上限并加 1 来对它们进行计数:

Dim comboitems() as Variant
Dim count as Long

comboitems = yourcombobox.Value

' array is 0-based so add one to get the count
count = UBound(comboitems) + 1
Run Code Online (Sandbox Code Playgroud)

如果数组是多维的,则可以这样读取值:

' array is 0-based so add one to get the count
count = UBound(comboitems, [dimension]) + 1

' where [dimension] is a 1-based index equivalent to the 'column' of the data
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!

*注意:多值字段通常是不明智的,因为 Access 不太支持它们,并且通常意味着您应该规范化表,即将多值字段分解到另一个表中。