索引的 VBA 组合框值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45170111/
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
VBA ComboBox Value by Index
提问by addohm
I've got a form that contains a combobox which contains the values
我有一个包含组合框的表单,其中包含值
With io6
.AddItem "90°"
.AddItem "180°"
.AddItem "270°"
.AddItem "360°"
End With
The member of this method I am actually using is .ListIndex. When a user selects 270 degrees, I am sending a 2 to a variable. When I read the variable, I want have the combobox correctly show the appropriate value. In other words, if the variable is 1, I want the combo box to show 180 degrees. Is that achievable withouta select\if statement that writes into .Value?
我实际使用的这个方法的成员是 .ListIndex。当用户选择 270 度时,我将向变量发送 2。当我读取变量时,我希望组合框正确显示适当的值。换句话说,如果变量为 1,我希望组合框显示 180 度。如果没有写入 .Value 的 select\if 语句,这是否可以实现?
Sub varChange(val as integer)
With comboBox
Select Case val
Case 1
.value = "90°"
Case 2
.value = "180°"
Case 3
.value = "270°"
Case 4
.value = "360°"
End Select
End With
End Sub
The most direct I can ask this question is, can the method element be set based on the index? Can I set the combo box element based on the index rather than having to write in a new value?
这个问题我能问的最直接的是,method元素可以根据索引来设置吗?我可以根据索引设置组合框元素,而不必写入新值吗?
回答by Sam
I'm not sure if I got it right, but I think you want to get the list index of the selected item. You can get that by
我不确定我是否做对了,但我认为您想获取所选项目的列表索引。你可以通过
x = io6.ListIndex + 1
The +1 is there since ListIndex is 0 based, but you wanted it 1 based.
And something completely different,
Remove the brackets. Method calls without return values does not use them in VBA
+1 是存在的,因为 ListIndex 是基于 0 的,但您希望它基于 1。
还有一些完全不同的东西,
去掉括号。没有返回值的方法调用不会在 VBA 中使用它们
Edit after comment
To take this the other way, i.e getting a value from an index value, do like this:
评论后编辑
要采取另一种方式,即从索引值中获取值,请执行以下操作:
y = io6.List(x - 1)
回答by braX
sValue = combobox.List(combobox.ListIndex,0)
sValue = combobox.List(combobox.ListIndex,0)
回答by hammythepig
The most direct I can ask this question is, can the method element be set based on the index? Can I set the combo box element based on the index rather than having to write in a new value?
这个问题我能问的最直接的是,method元素可以根据索引来设置吗?我可以根据索引设置组合框元素,而不必写入新值吗?
Yes,
I used the following line:
是的,
我使用了以下行:
io6.ListIndex = val - 1
So in your code it's:
所以在你的代码中它是:
Sub varChange(val as integer)
comboBox.ListIndex = val - 1
End Sub