访问VBA:如何计算ComboBox的项目?

问题描述 投票:1回答:2

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

我想用VBA来算一下。我期待找到类似下面的字符串,但我得到Compile error: Argument not optional

Me.<ComboBox_name>.ItemData.Count

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

Me.<ComboBox_name>.ItemSelected.Count

enter image description here

ms-access combobox count access-vba selection
2个回答
2
投票

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

也就是说,如果您将多值*表字段链接到Combobox,您可以使用具有多个选择的Combobox。如果是这种情况,那么.ItemsSelected属性中唯一可用的值是当Combobox具有焦点并且下降时。

解决此问题的方法是将Combobox的.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

如果数组是多维的,则以这种方式读取值:

' 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

我希望有所帮助!

*注意:多值字段通常是不明智的,因为它们很难被Access支持,通常意味着你应该规范化表格,即将多值字段分成另一个表格。


1
投票

要计算选项,它是:

Me!<ComboBox_name>.ListCount

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

Me!<ComboBox_name>.ListCount - Abs(Me!<ComboBox_name>.ColumnHeads)
© www.soinside.com 2019 - 2024. All rights reserved.