VBA - 在ComboBox中将类添加为项

时间:2013-10-25 21:17:21

标签: vba collections combobox

我有一个包含CSV信息的文本文件。 我希望每个条目中的一个字段填充组合框。 但是当用户从组合框中选择一个项目时,我想保留与其他数据的关系。

例如:

Dim c as Collection

c = ReadFile() 'returns a Collection of variant arrays to c

Dim info As Variant

For Each info In c
    'Let's say, for example, info(3) contains the human-friendly name of the item
    '(which may or may not be unique)
    'and info(0) contains the unique ID of the item (which I need to reference later)

    'I'd like to put:
    'combobox.AddItem(info)
    'but I'm getting errors unless I do something more specific, like:

    combobox.AddItem (info(3))

    'Can I preserve each info() object as a part of the combobox?
    'I know this can be done in .NET but I'm not so sure about VBA.

Next info

是否可以将我的“信息”集合存储在组合框中?

稍后在代码中,我希望使用类似的方便:

combobox.SelectedItem(0)

combobox.Value(0)

检索我的唯一ID。

1 个答案:

答案 0 :(得分:3)

我没有SolidWorks,因此我无法在该上下文中对此进行测试,但这是一个用Excel构建的示例。我打赌Combobox类足够相似。

Option Explicit
Dim colTemp As Collection

Public Sub Populate_Combobox()
    Dim arrThings() As Variant
    Dim varItem As Variant

    'This section constructs a data structure like you describe: a Collection of Variant Arrays
    Set colTemp = New Collection
    arrThings = Array(123, "fhdg", "Umbrella")
    colTemp.Add arrThings
    arrThings = Array(156, "afibewsrbeld", "Car")
    colTemp.Add arrThings
    arrThings = Array(34, "afifelbxcfbd", "Car")
    colTemp.Add arrThings
    arrThings = Array(247, "afisbdfheldd", "Shoe")
    colTemp.Add arrThings

    For Each varItem In colTemp
        'This adds the "human readable" name to the dropdown
        ComboBox1.AddItem varItem(2) 
    Next

End Sub

Private Sub ComboBox1_Change()
    'This handles the event that a user has changed their selection in the dropdown
    Dim i As Integer
    Dim arrThings As Variant

    'The index of the ComboBox selection is used to get the correct array out of the Collection
    arrThings = colTemp.Item(ComboBox1.ListIndex + 1)

    'Just to show it's the correct item...
    Dim strOutput As String
    For i = 0 To UBound(arrThings)
        strOutput = strOutput & " " & arrThings(i)
    Next
    MsgBox "The chosen item contains these: " & strOutput
End Sub

编辑:修正了一个问题,因为我未能使用Option Explicit,我意外地创建了一个未声明的变量。值得庆幸的是,它对代码的功能没有任何影响,但很容易就可以实现。不要犯我的错误 - 总是使用Option Explicit;)