今天继续讲用户窗体的列表框控件,因为内容实在多,所以单独一章
一、添加条目
之前提到过列表框添加项目的用法
Private Sub UserForm_Initialize()
With Me.ListBox1
.AddItem "1号选择"
.AddItem "2号选择"
.AddItem "3号选择"
.AddItem "4号选择"
.AddItem "5号选择"
End With
End Sub
还可以使用List属性:
Dim myList()
myList = Array("1月", "2月")
Me.ListBox1.List = myList
也可以引用单元格内容Application.Transpose是把Range变成横向的数组
Private Sub UserForm_Initialize()
Me.ListBox1.List = Application.Transpose(Sheets(1).Range("A1:A12"))
End Sub
二、添加唯一的条目
List是可以重复条目的,所以直接导入到ListBox里面也就会有重复条目了,那么怎么让导入的条目是唯一的呢?
办法也很简单,集合类型是不能重复滴,所以用集合类型的数据作为参数就可以啦。
大致思路和前面一样,先把EXCEL单元格内的内容插入到集合中,遇到重复的值会报错所以忽略错误,然后插入完了就逐个添加到列表中。
Private Sub UserForm_Initialize()
Dim myCollection As Collection
Dim allCells As Range, cell As Range
Dim item As Variant
Set myCollection = New Collection
Set allCells = Sheets("Sheet1").Range("A1:A12")
On Error Resume Next
For Each cell In allCells
myCollection.Add cell.Value, CStr(cell.Value)
Next
For Each item In myCollection
Me.ListBox1.AddItem item
Next
End Sub
三、确定选定的条目
添加完了条目,我们就需要确定用户点击完了,这用户到底点的是哪个类目
其实很简单啦,用户点击完了,ListBox的Value属性就是选择的值。咱们加个按钮用来输出试试
Private Sub CommandButton1_Click()
MsgBox Me.ListBox1.Value
End Sub
如果需要知道点击的是第几条,可以用ListB