vba 如何区分列表框中显示的文本和实际值。?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11062114/
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
How can I distinguish the text displayed in a listbox from a real value.?
提问by Francesco Bonizzi
I have a listbox with multiselect options. I populate it using the addItem
function.
I can't find any article about this on Google, but I need to distinguish from the text displayed in the listbox and a real value.
我有一个带有多选选项的列表框。我使用该addItem
函数填充它。我在 Google 上找不到任何关于此的文章,但我需要区分列表框中显示的文本和实际值。
For example:
例如:
shown hiddenvalue
-------- -----------
monday A1
tuesday A2
wednesday C7
etc.
等等。
Is it possible? How can I access these values?
是否可以?如何访问这些值?
回答by GSerg
For VBA listbox you want to:
对于 VBA 列表框,您要:
- Declare two columns (
ColumnCount = 2
). - Make the second one hidden:
ColumnWidths = ";0"
. - Declare the second column as bound (
BoundColumn = 2
) and the first column as textual (TextColumn = 1
). Have a procedure to add values:
Private Sub AddWithID(Text As String, ID As String) ListBox1.AddItem Text ListBox1.List(ListBox1.ListCount - 1, 1) = ID End Sub
- 声明两列 (
ColumnCount = 2
)。 - 隐藏第二个:
ColumnWidths = ";0"
. - 将第二列声明为绑定 (
BoundColumn = 2
),将第一列声明为文本 (TextColumn = 1
)。 有一个添加值的过程:
Private Sub AddWithID(Text As String, ID As String) ListBox1.AddItem Text ListBox1.List(ListBox1.ListCount - 1, 1) = ID End Sub
Now, for single-select listbox, you can use .Value
or .Text
to find out selected value/text.
现在,对于单选列表框,您可以使用.Value
或.Text
找出选定的值/文本。
For multi-select listbox, you can use .List(i, 0)
for text and .List(i, 1)
for value, where i
in an index of a row.
对于多选列表框,您可以使用.List(i, 0)
for text 和.List(i, 1)
for value,其中i
位于一行的索引中。
回答by Siddharth Rout
Another way... Using Collections.
另一种方式...使用集合。
Private HiddenValue As New Collection
Private Sub CommandButton1_Click()
AddItems "monday", "A1"
AddItems "tuesday", "A2"
AddItems "wednesday", "C7"
End Sub
Private Sub CommandButton2_Click()
MsgBox "Shown Value :" & ListBox1.List(ListBox1.ListIndex) & vbNewLine & _
"Hidden Value " & HiddenValue(ListBox1.ListIndex + 1)
End Sub
Private Sub AddItems(Text As String, ID As String)
ListBox1.AddItem Text
HiddenValue.Add ID
End Sub
SNAPSHOTS
快照