使用数组中的两个文本字段填充组合框

Populate Combobox with Two Text Fields from an Array

我正在尝试从数组中的 2 个单元格中获取值以填充用户窗体上组合框的文本字段。数组中的值如下所示:

A  1
B  2
C  3
B  4

我想在组合框文本字段中区分 B2 和 B4。该字段当前填充为 B。我希望它用 B 2 填充。这个问题部分与 this 问题有关。

我尝试使用 this that was linked from here but couldn't get the ListCount property to work. I used this to better understand arrays in a hope that it would provide some insight. I tried this approach but it doesn't populate the text field. WhereInArray looks like it is more for finding a value and also appears to be unique-value-dependent. I tried ,但它似乎被阵列绊倒了。任何帮助将不胜感激。

想象一下 Worksheets("Sheet1")

中的数据

像这样填充您的组合框 ComboBox1:遍历数据并使用 .AddItem 添加两个数据列的组合。

Private Sub UserForm_Initialize()
    Dim Data() As Variant 'array
    Data = Worksheets("Sheet1").Range("A1:B4").Value 'read data into array

    Me.ComboBox1.Clear

    Dim iRow As Long
    For iRow = LBound(Data, 1) To UBound(Data, 1)
        Me.ComboBox1.AddItem Data(iRow, 1) & " " & Data(iRow, 2)
    Next iRow
End Sub

然后您可以select您的项目如下:

并且您可以使用 Me.ComboBox1.Text:

检索值 B 2
Debug.Print Me.ComboBox1.Text 'returns B 2