如何用vba实现数据有效性下拉列表的多选?

在excel中可以为单元格添加数据有效性下拉列表,方便快速地选择要输入的内容,如下图所示:

但是数据有效性的下拉列表只能单选,不能多选。

这时候可以用ActiveX 列表框控件代替,如下图所示:

首先在工作表中插入一个ActiveX 列表框控件命名为“ListBox1”,然后在工作表Sheet1中添加如下代码:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Call ListAddItem
    With Sheet1.ListBox1
        .Left = Target.Offset(0, 1).Left
        .Top = Target.Top
        .Width = Target.Width
        .Height = Target.Height * 10
    End With
End Sub
Sub ListAddItem()
    Sheet1.ListBox1.Clear
    Dim oWK As Worksheet
    '列表项所在的工作表中
    Set oWK = Sheet2
    With oWK
        '添加列表项
        For i = 2 To .Range("a65536").End(xlUp).Row
            With Sheet1.ListBox1
                .ListStyle = fmListStyleOption
                .MultiSelect = fmMultiSelectMulti
                .AddItem oWK.Cells(i, "a").Text, i - 2
            End With
        Next i
    End With
End Sub
Private Sub ListBox1_Change()
    '响应列表框中选择了不同项目后的事件
    Dim arr()
    k = 0
    With Sheet1.ListBox1
         For i = 0 To .ListCount - 1
                If .Selected(i) = True Then
                    ReDim Preserve arr(k)
                    arr(k) = .List(i)
                    k = k + 1
                End If
            Next i
    End With
    sText = Join(arr, ",")
    Excel.ActiveCell = sText
End Sub
       

发表评论