我成功地成功地动态生成了ListBoxes。但是我现在正在努力解决并填充那些生成的ListBox。此外,我不知道如何激活那些ListBoxes的MultiSelect属性。只有ActiveX可以做到吗?
我首先尝试了ActiveX-userForm上的ListBoxes。现在,我在WorkSheet上切换回“普通”列表框。“ FS”是我正在处理的工作表的名称。为了理解:我遍历工作表FS上的列,并为每个列创建一个ListBox。在每个列表框中,将添加相应列的条目。
For i = 1 To 10
LastRow = FS.Cells(Rows.Count, i).End(xlUp).Row
With FS
Set lb = FS.Shapes.AddFormControl(xlListBox, 100, 10, 100, 100)
lb.ControlFormat.MultiSelect = 2
For Each cell In FS.Range(Cells(1, i), Cells(LastRow,i)).Cells
lb.ControlFormat.AddItem cell.Value 'This is the problematic line
Next cell
End With
Next i
我建议您这样做:
Sub test()
''''Declarations'''''''''''''''''''''''''''
Dim lb As ListBox '
Dim sht As Worksheet '
Dim rng As Range '
Dim cell As Range '
Dim i As Long '
'''''''''''''''''''''''''''''''''''''''''''''
Set sht = ThisWorkbook.Worksheets("Name of your worksheet")
For i = 1 To 10
With sht
Set rng = .Range(.Cells(1, i), .Cells(.Rows.Count, i).End(xlUp))
Set lb = sht.ListBoxes.Add(100 * i, 10, 100, 100) 'just an indicative way to create the List boxes without them overlapping
End With
lb.Name = "ListBox" & i
lb.MultiSelect = 2
For Each cell In rng
lb.AddItem cell.Value
Next cell
Next i
End Sub
更新(以覆盖所做的评论)
我更新了上面的代码,将列表框命名为“ ListBox1”,“ ListBox2”等,而不是“ List Box 1”等。
要引用其中一个列表框,您需要使用对的集合的引用ListBoxes
。该集合属于列表框所在的工作表。例如,要引用“ ListBoxi”,其中i = 1,2 ... n,您需要这样做:
sht.ListBoxes("ListBox" & i)
不幸的是.SelectedItems.Count
,我不知道可以与窗体控件“列表框”一起使用的方法。
考虑到这一点,例如,您可以找到“ ListBox1”的选定项数,如下所示:
Dim selectedItems As Long
selectedItems = 0
Set lb = sht.ListBoxes("ListBox" & 1)
For i = 1 To lb.ListCount Step 1
If lb.Selected(i) Then
selectedItems = selectedItems + 1
End If
Next i
If selectedItems = 0 Then
MsgBox "No user selected"
End If
请记住以下几点:
0
到有所1
不同。Listbox1.DoSomething
,它需要是一个ActiveX
控件而不是Form控件。
谢谢@Stavros!生成列表框现在可以正常工作,但现在在读取值时遇到问题。看来我无法从我命名为lb.name =“ ListBox”&i的那些生成的ListBox中读出项目。
If ListBox1.SelectedItems.Count = 0 Then MsgBox "No Item Selected" End If
-引发错误“找不到对象”@DXR我已经更新了我的帖子以回答您的评论。如果这解决了您的问题,请考虑接受它作为答案。
嗨,非常感谢您对@stavros的帮助!我有两个问题:1)为什么需要将变量“ i”定义为“ long”。“整数”就够了吗?2)是否可以在表单列表框上编程“ OnClick”事件?例如:在Listbox1中选择一个项目会自动生成另一个包含其他项目的Listbox。
@DXR,例如,您可以构建一个
Sub
inModule1
并使用.OnAction
列表框的属性。当创建列表框一样可以设置该属性lb.OnAction = "Module1.runThis"
,在这里runThis
是sub
希望每当被点击列表框运行。有关更多信息,建议您发布一个新问题