我在userform上创建了一个多选列表框。列表框中有9个项目。如何将这些选定的项目收集到一个句子中?
列表框包含退回支票的原因。列表框中的项目是较长字符串的标识符或占位符,因此选择“unsigned”会创建返回的字符串,“检查未签名”。
用户可以选择几个原因,因此根据选择,我需要格式为“x,y和z”或“y和z”或“z”的句子结构。 (例如:“支票未签署,支票已过期,支票为第三方支票。”)
似乎需要从选择中创建数组,选择计数,然后使用“If then”语句创建句子,但我很难过。 我可以计算所选项目,如果只选择了1个项目,我可以创建句子,但是复合句子让我感到难过。
答案 0 :(得分:11)
我有这个函数,它从列表框中返回一个选定项目的数组。我已从原始答案更新,以返回分隔字符串而不是所选项目数组:
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)
从那时起,你可以用“和”替换 last 逗号,你应该全部设置。
答案 1 :(得分:0)
这是非常基本的,我只是很快把它扔在一起,但可能适用于你想要做的事情:
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
答案 2 :(得分:0)
忘记REDim阵列概念 - 会让人感到困惑。收集多选选项的简单方法如下
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