如何使用来自两个不同列的数据填充组合框下拉列表?

How can I populate combobox dropdown with data from two different columns?

我正在努力用 VBA 构建我的第一个有用的文档,并且大部分时间我都能够插上电源,直到我得到我想要的碰巧工作,但我已经 运行撞墙。

我有一个 sheet,其中包含 "B" 列中的信息和 "i" 列中的信息,我想在我的用户窗体中将其添加到 ComboBox 行项目中。

基本上,"B" 列包含任务,"i" 列包含截止日期。当用户打开我的 ComboBox 的下拉列表时,我希望每一行都显示任务名称和截止日期,这样重复的任务就不会混淆。

我已经尝试了六种方法,而且我看到了一个接一个的错误。

我怀疑我需要构建一个数组、一个列表对象或其他东西,但是当我尝试那样做时,一切都坏了。

这是我第一次尝试的非功能性子程序。谁能告诉我如何实现我的梦想?

`Private Sub UserForm_Initialize()

Dim task As String  'representing each cell in my "B" column, which contains an entry
Dim due As String   'representing each cell in my "i" column, which contains an entry
Dim NumElements As Integer  'representing number of rows populated in my document
Dim ws As Worksheet 'for referencing specific sheet

NumElements = Sheets("Engine").Range("$B")    'Yields number of entries using a "=COUNTA" formula in the document.
'I would love to have the number of entries calculated within vba, instead of in the document,
'but I haven't been able to figure that out.

Set ws = Sheets("Tasks")    'the sheet with my database in it

'attempting to pull data from each cell in "B" column to populate first half of each line in ComboBox "Combo_Task_Select"
For Each task In ws.Range("$B:$B$" & NumElements)
        Me.Combo_Task_Select.AddItem task.Value 'populate with data from variable "task"
'attempting to pull data from each cell in "i" column to populate second half of each line in ComboBox "Combo_Task_Select"
                For Each due In ws.Range("$I:$I$" & NumElements)
                Me.Combo_Task_Select.AddItem due.Value  'populate with data from variable "due"
        Next due    'attempt at keeping the looping "due" and "task" variables in synch, by nestling "next"s
Next task

End Sub`

NumElements = range(range("b8"), range("b8").End(xlDown)).Rows.Count 为您提供列中的元素数,从 B8 开始直到第一个空单元格以上。

对于下拉列表,您可以选择单列组合框或多 (2) 列组合框。我建议使用 2 列版本,它并不比单列复杂多少。您可以分两步填充组合框:将值填充到数组,然后将该数组加载到组合框。 (你选择的方案也很好,但我更喜欢这种方式,因为它更容易调试。)

2栏版本:

Dim arr(), i As Long
Redim arr(1 to NumElements,1 to 2)

For i=1 to NumElements
     arr(i,1)=cells(7+i,2)     ' column B
     arr(i,2)=cells(7+i,9)     ' column I
Next 
Me.Combo_Task_Select = arr

完成。请记住在表单设计器中设置列数 属性。或者您可以使用 Me.Combo_Task_Select.ColumnCount=2

动态设置它

单列版本:您需要从 2 个单元格中生成一个字符串值,如下所示:

Redim arr(1 to NumElements)
For i=1 to NumElements
    arr(i)=Left(cells(7+i,2) & worksheetFunction.rept(" ",10), 10) & cstr(cells(7+i,9))
next

根据任务的最大长度调整“10”。