VBA⾃学应⽤(12)——允许列表框多项选择和多列⽂章⽬录
⼀、允许多项选择
代码如下
Private Sub UserForm_Initialize()
arr = Sheets("产品表").Range("a1").CurrentRegion
With ListBox1
'设置列表框属性
.List = arr
.MultiSelect = fmMultiSelectExtended
.ColumnCount =UBound(arr,2)
.ListStyle = fmListStyleOption
End With
End Sub
object.MultiSelect [= fmMultiSelect]
fmMultiSelect设置值
常量值说明
fmMultiselectsingle0只可选择1个条⽬(默认)
fmMultiselectMulti1按space键或单击以选中列表中1个条⽬或取消选中fmMultiselectExtended2按shift键可以扩展选中条⽬,按ctrl的同时单击可以选择多个
object.liststyle [= fmliststyle]
fmliststyle设置值
常量值说明
fmliststyleplain0外观与常规的列表框相似,条⽬的背景为⾼亮
fmliststyleoption1显⽰选项按钮,或显⽰⽤于多重选择列表的复选框(默认)。当⽤户选中组中的条⽬时,与该条⽬相关的选项按钮即被选中,⽽
该组其他条⽬的选项按钮被取消选中
⼆、设置多列列表框
Private Sub UserForm_Initialize()
Dim lngLast As Long
lngLast = Sheet1.Cells(Rows.Count,1).End(xlUp).Row With lstData
.ColumnCount =7
vba自学好学吗.ColumnWidths ="45;45;45;45;45;45;45"
.BoundColumn =1
.ColumnHeads =True
.RowSource = Sheet1.Range("A2:G"& lngLast).Address End With
End Sub
object.boundcolumn [= variant],boundcolumn属性标识多列组合框或列表框值得数据来源
boundcolumn属性值
值说明
0将被选中列表项的listindex属性的值赋予控件
1或⼤于1将指定列中的值赋予控件。当采⽤此属性时,列从1开始计数(默认值)
三、将多列列表框的数据写⼊⼯作表
Private Sub lstData_Click()
Dim lngLast As Long
Dim i As Byte
lngLast = Sheet1.Cells(Rows.Count,1).End(xlUp).Row +1
For i =1To lstData.ColumnCount
Sheet1.Cells(lngLast, i)= lstData.Column(i -1)
Next i
End Sub
当将多列列表框的数据写⼊⼯作表中时,只能将boundcolumn属性所指定列中的值写⼊⼯作表,⽽不能将选中的整⾏内容写⼊⼯作表中。如果需要将选中⾏的整⾏内容写⼊⼯作表,则需要⽤到以上循环。
当然也可以⽤数组的⽅式写⼊数据到⼯作表,代码如下
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
'双击的时候也可以更改数据
Dim crr()
Dim m As Long
For i =0To ListBox1.ListCount -1
If ListBox1.Selected(i)=True Then
m = m +1
ReDim Preserve crr(1To ListBox1.ColumnCount,1To m)
For j =0To ListBox1.ColumnCount -1
crr(j +1, m)= ListBox1.List(i, j)
Next
End If
Next
If m >0Then ActiveCell.Resize(m, j)= Application.Transpose(crr)
End Sub
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论