首页 > 解决方案 > 如何使用来自两个不同列的数据填充组合框下拉列表?

问题描述

我正在努力使用 VBA 构建我的第一个有用的文档,并且大多数情况下我已经能够插入,直到我得到我想要的工作,但我遇到了墙。

我有一张表,其中包含“B”列中的信息和“i”列中的信息,我想在我的用户窗体中将其放入 ComboBox 行项目中。

本质上,“B”列包含任务,“i”列包含截止日期。当用户打开我的组合框的下拉菜单时,我希望每一行都显示任务名称和截止日期,这样重复的任务就不会混淆。

我已经尝试了六种方法,并且我看到一个又一个错误。

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

这是我第一次尝试的非功能性潜艇。有人可以告诉我如何做我梦寐以求的事情吗?

`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$2")    '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$8:$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$8:$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`

标签: vbacomboboxmultiple-columnsuserform

解决方案


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”。


推荐阅读