我有这个函数,它从列表框中返回一个选定项目的数组。我已从原始答案更新为返回分隔字符串而不是所选项目的数组:
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
您可以通过分配给数组来调用它:
Dim mySentence as String
mySentence = GetSelectedItems(MyUserForm.MyListBox)
从那时起,您只需将最后一个逗号替换为“和”,您就应该准备好了。