函数将所有选中的项目从列表框中返回到单元格中
我想将活动的x列表框中的所有选中项目放到工作表上的一个单元格中。 我有这个代码,正是我想要的作为一个子:
Private Sub CommandButton1_Click() Dim lItem As Long Dim outstr As String For lItem = 0 To ListBox1.ListCount - 1 If ListBox1.Selected(lItem) = True Then outstr = outstr & ListBox1.List(lItem) & "/" End If Next Range("A1") = Left(outstr, Len(outstr) - 1) End Sub
这将所有检查的项目放入单元格a1。
我把它转换成这样的函数:
Function CopySelected(lb As MSForms.ListBox) As String Dim lItem As Long Dim outstr As String For lItem = 0 To lb.ListCount - 1 If lb.Selected(lItem) = True Then outstr = outstr & lb.List(lItem) & "/" End If Next CopySelected = Left(outstr, Len(outstr) - 1) End Function
但是我不能给这个函数正确的参数来返回相同的子。 我需要把什么作为论据?
我尝试了以下内容:
=Copyselected(Sheet1.ListBox1) =Copyselected(Sheet1.ListBoxes("ListBox1")) =Copyselected(Sheet1.Shapes("ListBox1").OLEFormat.Object) =Copyselected(Worksheets("Sheet1").ListBox1)
似乎没有任何工作。 函数是不正确还是通过?
使用下面的代码:
Public Function GetAllSelected(strListBox As String) Dim lItem As Long Dim outstr As String With Worksheets(1).OLEObjects(strListBox).Object For lItem = 0 To .ListCount - 1 If .Selected(lItem) = True Then outstr = outstr & .List(lItem) & "/" End If Next lItem End With GetAllSelected = Left(outstr, Len(outstr) - 1) End Function
然后调用它作为一个string传递ListBox的名称:
=GetAllSelected("ListBox1")
请注意,此时必须知道表单。 如果您需要将表单名称(以及)传递给该函数,则必须相应地调整代码。
更新:
对于使用ListBox1_Change()
事件的下面的注释中概述的主动方法,结果将如下所示:
但是,在这种情况下,每个ListBox都有一个过程,而且子结果总是写入同一个单元格(硬编码)。
使用@Ralph的代码,你也应该可以使用你的函数。
尝试…
=Copyselected(Sheet1.OLEObjects("ListBox1").Object)