1

我有一个包含 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。

4

1 回答 1

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 ;)

于 2013-10-25T22:35:23.410 回答