Excel宏以显示多选列表框的所有选择

时间:2013-10-09 14:06:40

标签: excel vba excel-vba

我想创建一个带有多选的列表框的Excel工作表文件:

item1 
item2
item3
item4
...
..

然后,当我从该列表框中选择示例item1item3时,所选项目将填充在另一个显示为

的单元格上
item1 - item 2  are selected 

我尝试的解决方案是创建多选列表框,我附加了一个宏,然后我尝试循环列表框显示所选项目到一个单元格,但我不知道写宏,我是不是Excel专家我需要这样做。

提前致谢

1 个答案:

答案 0 :(得分:2)

这应该工作鉴于你开始使用Fresh No Items Selected ListBox。我选择在已经生成的字符串中添加和删除项目,而不是为了性能原因而在每次选择/取消选择时循环每个对象。这是一个选项,但这应该运行得更顺畅。但是,如果您已经在ListBox中选择了项目,则在取消选择然后重新选择它们之前,这将不会考虑它们。

此选项与每次循环所有值之间的另一个区别是,使用此方法时,它会按照选择它们在ListBox中的顺序与它们在ListBox中的顺序相反的顺序添加选择/值,这可能是积极的消极或漠不关心你的目的,但我想应该加入。

Private Sub ListBox1_Change()

Dim lngCurrentItem As Long
Dim strCurrentItem As String
Dim strAllSelectedItems As String
Dim rngOutput As Range

Set rngOutput = [J1]
lngCurrentItem = ListBox1.ListIndex

strAllSelectedItems = rngOutput
strAllSelectedItems = Replace(strAllSelectedItems, " Are Selected", "")
strAllSelectedItems = Replace(strAllSelectedItems, " Is Selected", "")

strCurrentItem = ListBox1.List(lngCurrentItem)

If ListBox1.Selected(lngCurrentItem) Then
    If strAllSelectedItems = "No Items Selected" Then
        rngOutput = strCurrentItem & " Is Selected"
    Else
        rngOutput = strAllSelectedItems & " - " & strCurrentItem & " Are Selected"
    End If
Else
    strAllSelectedItems = Replace(strAllSelectedItems, " - " & strCurrentItem, "")
    strAllSelectedItems = Replace(strAllSelectedItems, strCurrentItem, "")
    If strAllSelectedItems = "" Then
        rngOutput = "No Items Selected"
    ElseIf InStr(1, strAllSelectedItems, " - ", vbTextCompare) > 0 Then
        rngOutput = strAllSelectedItems & " Are Selected"
    Else
        rngOutput = strAllSelectedItems & " Is Selected"
    End If
End If

End Sub

如果你想每次循环整个列表(如果你的列表框足够小,你就不会发现速度差别太大,只要确保你的列表框没有像整个列一样超过100万个细胞,你应该没问题)

Private Sub ListBox1_Change()

Dim lngCurrentItem As Long
Dim strCurrentItem As String
Dim strAllSelectedItems As String
Dim rngOutput As Range

Set rngOutput = [J1]

strAllSelectedItems = ""

For i = 0 To ListBox1.ListCount - 1
    strCurrentItem = ListBox1.List(i)

    If ListBox1.Selected(i) Then
        If strAllSelectedItems = "" Then
            strAllSelectedItems = strCurrentItem
        Else
            strAllSelectedItems = strAllSelectedItems & " - " & strCurrentItem
        End If
    End If

Next i

If strAllSelectedItems = "" Then
    rngOutput = "No Items Selected"
ElseIf InStr(1, strAllSelectedItems, " - ", vbTextCompare) > 0 Then
    rngOutput = strAllSelectedItems & " Are Selected"
Else
    rngOutput = strAllSelectedItems & " Is Selected"
End If

End Sub