Excelmacros显示多选列表框的所有select

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

item1 item2 item3 item4 ... .. 

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

 item1 - item 2 are selected 

我试过的解决scheme是创build多选列表框,我附加了一个macros,然后我试图循环在列表框显示选定的项目到一个单元格,但我不知道写macros,我不是Excel专家需要这样做。

提前致谢

这应该工作鉴于你开始与新鲜没有项目select列表框。 我select添加和删除已经创build的string的项目,而不是循环每个对象的每个select/取消select的性能原因。 这是一个select,但这应该运行得更顺畅。 但是,如果您已经在列表框中select了某些项目,那么在取消select之后,这些项目将不会考虑它们,然后重新select它们。

这个选项和每次循环所有值之间的另一个区别在于,使用这个方法,它会按照它们在列表框中相同顺序添加select/值的顺序,这可能是一个正值消极或漠不关心你的目的,但我想我应该补充说。

 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