【问题标题】:How can I populate combobox dropdown with data from two different columns?如何使用来自两个不同列的数据填充组合框下拉列表?
【发布时间】:2019-01-07 08:07:14
【问题描述】:

我正在努力使用 VBA 构建我的第一个有用的文档,并且大部分时间我已经能够插入,直到我得到我想要的工作,但我遇到了障碍。

我有一张表,其中包含“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$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`

【问题讨论】:

    标签: vba combobox multiple-columns userform


    【解决方案1】:

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

    【讨论】:

    • 这立即解决了我的问题。 AcsEmo,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多