ms excel vba 用不同的列要求填充列表框

ms excel vba populate listbox with varying column requirements

背景

我正在 ms excel 中开发一个用户表单,以便为分布在多个工作表中的数据提供 'dashboard'。用户窗体显示一个组合框,并从该选择中填充列表框。用户窗体还允许通过 'COPY' 按钮复制列表框信息。列表框的行源可以是单个列(例如 Budget!$L$191)或多个列和行(例如 JKG.Slave!$I$38:$JM$44)。

我在列表框属性中选择了 'MultiSelect' 属性。

挑战

如何在多列(如果需要)列表框中显示所有行源数据?
如何动态捕获支持多列列表框所需的列数?
我可以使用变量来捕获列数并让它在运行时填充列表框吗?

项目代码示例

Public Sub ComboBox1_Change()

Dim cSelect As String
Dim lcount As Integer

cSelect = UserForm2.ComboBox1.Value

UserForm2.ListBox1.RowSource = cSelect

lcount = UserForm2.ComboBox1.ColumnCount

MsgBox lcount

End Sub  

变量 lcount returns 一 (1) 即使行源是多行和多列选择。

谢谢大家的帮助。

要将项目添加到列表框,只需定义您的范围并遍历它们以添加到列表。

现在我刚刚指定了一个任意范围,您可以使该范围动态化并满足您的需要,代码会为您调整列数和行数。您不需要为列数弄乱 listbox 属性,因为它是通过编程方式完成的以适应您问题的动态性质。

   Dim x      
   Dim i As Long
   Dim y As Long
   Dim yy As Long

    x = Range("C1:E20") ' change this to suit the range you want       
    y = (UBound(x, 2) - LBound(x, 2))

    ListBox1.ColumnCount = y + 1
    For i = 0 To UBound(x) - 1
      With ListBox1
       .AddItem
        For yy = 0 To y
          .List(i, yy) = x(i + 1, yy + 1)
        Next
      End With
    Next    

然后要得到多个select,改变列表框的属性,

在这里,我修改了对 的回答,以调整 ComboBox 或 ListBox 的 Column 计数和 ListWidths

用法

ConfigureComboOrListBox ListBox1

Private Sub ConfigureComboOrListBox(LCBox As Object)
    Dim arrData, arrWidths
    Dim x As Long, y As Long, ListWidth As Double
    arrData = LCBox.List
    ReDim arrWidths(UBound(arrData, 2))

    For x = 0 To UBound(arrData, 1)
        For y = 0 To UBound(arrData, 2)

            If Len(arrData(x, y)) > arrWidths(y) Then arrWidths(y) = Len(arrData(x, y))

        Next
    Next

    For y = 0 To UBound(arrWidths)

        arrWidths(y) = arrWidths(y) * LCBox.Font.Size
        ListWidth = ListWidth + arrWidths(y)
    Next

    With LCBox
        .ColumnCount = UBound(arrWidths) + 1
        .ColumnWidths = Join(arrWidths, ";")
        .ListWidth = ListWidth
    End With

End Sub