How do I return multi select listbox values into a sentence using Word VBA?

天涯浪子 提交于 2019-12-08 22:12:30

I have this function which returns an array of selected items from a listbox. I have updated from my original answer to return a delimited string instead of an array of selected items:

Public Function GetSelectedItems(lBox As MSForms.ListBox) As String
'returns an array of selected items in a ListBox
Dim tmpArray() As Variant
Dim i As Integer
Dim selCount As Integer
    selCount = -1
    '## Iterate over each item in the ListBox control:
    For i = 0 To lBox.ListCount - 1
        '## Check to see if this item is selected:
        If lBox.Selected(i) = True Then
            '## If this item is selected, then add it to the array
            selCount = selCount + 1
            ReDim Preserve tmpArray(selCount)
            tmpArray(selCount) = lBox.List(i)
        End If
    Next

    If selCount = -1 Then
        '## If no items were selected, return an empty string
        GetSelectedItems = "" ' or "No items selected", etc.
    Else:
        '## Otherwise, return the array of items as a string,
        '   delimited by commas
        GetSelectedItems = Join(tmpArray, ", ")
    End If
End Function

You can call this by assigning to an array:

Dim mySentence as String
mySentence = GetSelectedItems(MyUserForm.MyListBox)

From that point, you could just replace the last comma with a " and" and you should be all set.

This is very basic and I just quickly threw it together, but may work for what you're trying to do:

Private Sub ListBox1_Change()

    If ListBox1.Selected(0) = True Then
        msg1 = ListBox1.List(0)
    End If

    If ListBox1.Selected(1) = True Then
        msg2 = ListBox1.List(1)
    End If

    If ListBox1.Selected(2) = True Then
        msg3 = ListBox1.List(2)
    End If

    MsgBox msg1 & ", " & msg2 & ", " & msg3

End Sub

Forget the REDim array concept- can get confusing. A simple way to collect multiselect choices is the following

Sub SelectMulti()
picklist1 = ""
For i = 0 To ListBox1.ListCount - 1
   If ListBox1.Selected(i) = True Then
      Debug.Print i    ' optional 
      If picklist1 = "" Then
         picklist1 = ListBox1.List(i)
       Else
         picklist2 = ListBox1.List(i)
         picklist1 = picklist1 & ";" & picklist2
       End If
    End If
Next
Debug.Print picklist1

End sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!