如何动态生成和填充 VBA 中的列表框?

How to generate and populate Listboxes in VBA dynamically?

我正在尝试动态生成列表框(当前在用户窗体中)(取决于源 sheet 中使用的列)并使用属于这些列的条目填充它们。

例如:

用户窗体应生成两个列表框(一个用于 A 列,一个用于 B 列)并使用这些列的相应条目填充它们。

我尝试遍历列表框,但我不断收到错误消息,因为我不知道如何正确获取语法。变量 Lastrow 给出了列中非空单元格的数量并且功能正常(为了更好地查看相关代码,未显示代码。

我是这样生成Listbox的:

Dim i As Integer
For i = 1 To 21
    Set LstBx = UserForm1.Controls.Add("Forms.Listbox.1", Name:="Listbox" & i)
Next i

填充列表框对我来说似乎更难:

Dim i As Integer
Dim LB As String
Dim cell As Range

For i = 1 To 21
For Each cell In SourceSheet.Range(Cells(1, i), Cells(LastRow, i)).Cells
    LB = "Listbox" + i
    LB.AddItem cell.Value
Next cell

下面结合了生成和人口,是我试图修复的实际代码:

Dim i As Integer
Dim LB As String
Dim cell As Range

For i = 1 To 21

'Generate
Set LstBx = UserForm1.Controls.Add("Forms.Listbox.1", Name:="Listbox" & i)

'Populate
For Each cell In SourceSheet.Range(Cells(1, i), Cells(LastRow, i)).Cells
    LB = "Listbox" + i

    'the following is the crucial part I am losing hope on:
    'It seems that it is not possible to address Listboxes this way but i cant find another way:
    LB.AddItem cell.Value

Next cell

我期望根据列的动态数量生成和填充列表框。但是我在循环时特别努力将项目添加到正确的 ListBox 中。最后,我的目标只是将所有列和相应条目传输到有关动态列和行范围的列表框中。

您可以像这样按名称引用列表框:

Me.Controls("Listbox" & i).addItem cell.value

在这种情况下,我是用户表单。