0

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

item1 
item2
item3
item4
...
..

然后,当我选择示例item1item3从该列表框中选择的项目被填充到另一个单元格中,并显示为

item1 - item 2  are selected 

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

提前致谢

4

1 回答 1

2

鉴于您从一个新鲜的未选择项目列表框开始,这应该可以工作。我选择从已创建的字符串中添加和删除项目,而不是出于性能原因在每次选择/取消选择时循环每个对象。这是一个选项,但这应该运行得更顺畅。但是,如果您已经在 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

如果您想每次都循环整个列表(如果您的列表框足够小,您不会真正注意到速度上有太大的差异,只要确保您的列表框没有设置为像超过 1 的整个列百万个细胞,你应该没问题)

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
于 2013-10-09T16:26:29.343 回答