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

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

How can I distinguish the text displayed in a listbox from a real value.?

vba

提问by Francesco Bonizzi

I have a listbox with multiselect options. I populate it using the addItemfunction. 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 列表框,您要:

  1. Declare two columns (ColumnCount = 2).
  2. Make the second one hidden: ColumnWidths = ";0".
  3. Declare the second column as bound (BoundColumn = 2) and the first column as textual (TextColumn = 1).
  4. 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
    
  1. 声明两列 ( ColumnCount = 2)。
  2. 隐藏第二个:ColumnWidths = ";0".
  3. 将第二列声明为绑定 ( BoundColumn = 2),将第一列声明为文本 ( TextColumn = 1)。
  4. 有一个添加值的过程:

    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 .Valueor .Textto 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 iin 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

快照

enter image description here

在此处输入图片说明