vba 获取 listBox.selectedItems 的文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28176259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get text of listBox.selectedItems?
提问by Jason
I have a listBox that displays members of a distribution group. I have the listbox setup for multisimple selection to select more than one member. I'm trying to do a loop to get the text of the selected items(index's). Here is my code which works fine for the first item. On the second item it crashes and says "Index was outside the bounds of the array." I will be taking these members and placing them in the To: field of a meeting request. So I need to to be formatted like this: member1;member2. I'm just using the MsgBox to test what I'm getting back. But I'm guessing I would need to add to an array. Please help!
我有一个显示通讯组成员的列表框。我有多个简单选择的列表框设置来选择多个成员。我正在尝试做一个循环来获取所选项目(索引)的文本。这是我的代码,它适用于第一项。在第二项上,它崩溃并显示“索引超出数组范围”。我将把这些成员放在会议请求的收件人:字段中。所以我需要这样格式化:member1;member2。我只是使用 MsgBox 来测试我返回的内容。但我猜我需要添加到一个数组中。请帮忙!
For i = 0 To (myListBox.Items.Count - 1)
If myListBox.GetSelected(i) Then
MsgBox(myListBox.SelectedItems(i))
End If
Next
采纳答案by Chrismas007
Re-read the question and I think you want to store this as a string. This should do what you are looking for:
重新阅读问题,我认为您想将其存储为字符串。这应该做你正在寻找的:
Documentation on ListBox.Selected()
Dim MailStr as String
MailStr = ""
If myListBox.SelectedItems.Count = 0 Then
MsgBox "No User Selected"
Exit Sub
End If
For i = 0 to (myListBox.Items.Count - 1)
If myListBox.Selected(i) Then
MailStr = MailStr & myListBox.Items.Item(i) & "; "
End If
Next i
You can also try:
你也可以试试:
Dim assets As String
assets = ""
For Each item In assetListBox.SelectedItems
If assets = Nothing Then
assets = item
'Outputs 1 item "Member1"
MsgBox(assets)
Else
assets = assets & "; " & item
'Outputs 2 items in format "member1; member2"
MsgBox(assets)
End If
Next
回答by Jason
This is what worked the way I want it.
这就是我想要的方式。
Dim assets As String
assets = ""
For Each item In assetListBox.SelectedItems
If assets = Nothing Then
assets = item
'Outputs 1 item "Member1"
MsgBox(assets)
Else
assets = assets & "; " & item
'Outputs 2 items in format "member1; member2"
MsgBox(assets)
End If
Next