vba 没有选择的组合框当前值的 ListIndex

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3312185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 11:54:46  来源:igfitidea点击:

ListIndex of current value of combobox without selection

excelvbacombobox

提问by Lance Roberts

In VBA, the ListIndex property of a Combobox shows the index (starting at 0) of the item selected in the overall list (array) of values in the Combobox. It shows -1 if there is no selection made.

在 VBA 中,组合框的 ListIndex 属性显示组合框中值的整个列表(数组)中所选项目的索引(从 0 开始)。如果没有选择,则显示 -1。

When I bring up a sheet in Excel with a Combobox and the last value in it, it comes up with a ListIndex of -1, instead of the actual ListIndex of the item.

当我在 Excel 中调出一个带有组合框的工作表和其中的最后一个值时,它出现的 ListIndex 为 -1,而不是该项目的实际 ListIndex。

What is the trick in VBA to quickly getting the ListIndex of the current non-selected value?

VBA 中快速获取当前非选定值的 ListIndex 的技巧是什么?

I know I could manually check the array myself (the .List property), but I'm hoping that VBA has some quicker way to do this.

我知道我可以自己手动检查数组(.List 属性),但我希望 VBA 有一些更快的方法来做到这一点。

回答by JimmyPena

From VBA Help on the ListIndexProperty:

来自ListIndex属性的VBA 帮助:

The ListIndex property contains an index of the selected row in a list. Values of ListIndex range from –1 to one less than the total number of rows in a list (that is, ListCount – 1). When no rows are selected, ListIndex returns –1. When the user selects a row in a ListBox or ComboBox, the system sets the ListIndex value.

ListIndex 属性包含列表中所选行的索引。ListIndex 的值范围从 –1 到比列表中的总行数少 1(即 ListCount – 1)。当未选择任何行时,ListIndex 返回 –1。当用户在 ListBox 或 ComboBox 中选择一行时,系统会设置 ListIndex 值。

So I assume you aren't selecting anything, but trying to read the selected value. That might explain why ListIndex returns -1.

所以我假设你没有选择任何东西,而是试图读取选定的值。这或许可以解释 ListIndex 返回 -1 的原因。

回答by marcp

This works for me to retrieve the index of the displayed item in the combo.

这对我来说可以检索组合中显示项目的索引。

        Dim dst As Worksheet: Set dst = Worksheets("MyData")
        MsgBox (dst.OLEObjects("combobox1").Object.ListIndex)