用户窗体列表框填充范围

Userform listbox populate with range

有什么方法可以按单元格范围填充列表框或用户表单中的其他功能?

我想将我选择的每个列放入 1 个列表框中,如:

.

例如 A2:U100 没有为每一列创建新的列表框?

现在我是这样做的:

ListBox1.List = Application.Worksheets("Můj_Ranking").Range("B2:B" & lastRw).Value
ListBox2.List = Application.Worksheets("Můj_Ranking").Range("C2:C" & lastRw).Value
ListBox3.List = Application.Worksheets("Můj_Ranking").Range("D2:D" & lastRw).Value
ListBox4.List = Application.Worksheets("Můj_Ranking").Range("E2:E" & lastRw).Value
ListBox5.List = Application.Worksheets("Můj_Ranking").Range("F2:F" & lastRw).Value
ListBox6.List = Application.Worksheets("Můj_Ranking").Range("G2:G" & lastRw).Value
ListBox7.List = Application.Worksheets("Můj_Ranking").Range("H2:H" & lastRw).Value
ListBox8.List = Application.Worksheets("Můj_Ranking").Range("I2:I" & lastRw).Value
ListBox9.List = Application.Worksheets("Můj_Ranking").Range("J2:J" & lastRw).Value
ListBox10.List = Application.Worksheets("Můj_Ranking").Range("K2:K" & lastRw).Value
ListBox11.List = Application.Worksheets("Můj_Ranking").Range("L2:L" & lastRw).Value

还没有测试列表框,但这是我用记录集的结果填充组合框的方法

 Function Fill_Combobox(ByRef cbo As ComboBox, ByVal rs As ADODB.Recordset, ByVal colWidth As String)
    Dim aryColumnWidth() As String
    Dim i As Integer

    aryColumnWidth = Split(colWidth, ";")
    cbo.Clear
    cbo.ColumnCount = UBound(aryColumnWidth) + 1
    cbo.ColumnHeads = False
    cbo.ColumnWidths = colWidth

    Do Until rs.EOF
        With cbo
            .AddItem
            For i = 0 To UBound(aryColumnWidth)
                .List(.ListCount - 1, i) = rs.Fields(i)
            Next
        End With
        rs.MoveNext
    Loop
End Function 

对于列表框,它的工作方式应该类似。调用 AddItem 方法向列表框添加一个新条目,然后通过访问列表元素来填充它

所以您确实想要一个包含多列的列表框,这样的事情应该有所帮助:

With ListBox1
    .ColumnCount = 11
    .ColumnWidths = "50;50;50;50;50;50;50;50;50;50;50"
    .ColumnHeads = False
    .RowSource = "=Můj_Ranking!B2:L" & LastRw
    .MultiSelect = fmMultiSelectMulti
End With

或者如何遍历控件:

For i = 1 To 11
    With Application.Worksheets("Můj_Ranking")
         Controls("ListBox" & i).List = .Range(ColLet(i) & "2:" & ColLet(i) & lastRw).Value
    End With
Next i

而且大多数控件还有 .RowSource 属性! ;)

以及获取列字母的函数:

Public Function ColLet(x As Integer) As String
With ActiveSheet.Columns(x)
    ColLet = Left(.Address(False, False), InStr(.Address(False, False), ":") - 1)
End With
End Function

假设我没看错你的问题,这应该添加一行,其中包含你在单个 ListBox 中的列数。

for i = 2 to lstRw
    With ListBox1
        .AddItem Application.Worksheets("Můj_Ranking").Range("B" & i).value
        .List(.ListCount - 1 ,1) = Application.Worksheets("Můj_Ranking").Range("C" & i).Value
        .List(.ListCount - 1 ,2) = Application.Worksheets("Můj_Ranking").Range("D" & i).Value

        'And so on for each column
        .List(.ListCount - 1 ,10) = Application.Worksheets("Můj_Ranking").Range("L" & i).Value
    End With
next i

请记住在您的用户窗体上编辑 ListBox 控件的列数属性,它不会起作用:)