如何在Excel VBA中显示多列组合框?

时间:2018-05-14 05:49:54

标签: excel vba combobox

我编写了填充ComboBox的代码,并将BoundColumnColumnCount值设置为2.

我的要求是在ComboBox中显示材质ID和材质描述,以使其易于使用。

但是当我运行UserForm时,它只显示第二列(即材料名称)。我还想在两个变量中单独捕获选择值和两个值,以便进一步处理。

我在UserForm的 initialize 事件中调用此宏。

Sub inittCode()

    Dim tcodelist() As String
    Dim tnamelist() As String

    'Activates master data sheet
    Worksheets("MD").Activate
    mylr = Cells(Rows.Count, 1).End(xlUp).Row

    'Calculate range size to initialize array
    Size = WorksheetFunction.CountA(Worksheets(1).Columns(1))

    ReDim tcodelist(Size)
    ReDim tnamelist(Size)

    'fill the first array
    For X = 2 To mylr
        tcodelist(X - 1) = Cells(X, 1)
    Next X

    'Adjust Array size to remove null values
    For a = 0 To mylr - 1
        tcodelist(a) = tcodelist(a + 1)
    Next a
    ReDim Preserve tcodelist(Size - 2)

    'Fill second array
    For x1 = 2 To mylr
        tnamelist(x1 - 1) = Cells(x1, 2)
    Next x1

    'Remove null values and adjust size
    For b = 0 To mylr - 1
        tnamelist(b) = tnamelist(b + 1)
    Next b
    ReDim Preserve tnamelist(Size - 2)

    'Fill combobox with array values
    MD_initform.matselcb.ColumnCount = 1
    MD_initform.matselcb.List = tcodelist
    MD_initform.matselcb.ColumnCount = 2
    MD_initform.matselcb.List = tnamelist

End Sub

1 个答案:

答案 0 :(得分:0)

如果要显示多个列,则需要将项列表作为二维数组传递。第一个索引用于行,第二个用于列。

如果不了解代码的详细信息,请执行类似

的操作
Dim tlist() As String
ReDim tlist(Size, 2)  ' Declare 2-dimensional array for "Size" rows and 2 cols
...
tlist(X - 1, 1) = Cells(X, 1)    ' Codes
...
tlist(x1 - 1, 2) = Cells(x1, 2)  ' Names

' Fill combobox with array values
MD_initform.matselcb.ColumnCount = 2
MD_initform.matselcb.List = tlist