如何使用Word VBA将多选列表框值返回到句子中?

问题描述 投票:1回答:3

我在userform上创建了一个多选列表框。列表框中有9个项目。如何将这些选定的项目收集到一个句子中?

列表框包含返回支票的原因。列表框中的项目是较长字符串的标识符或占位符,因此选择“unsigned”会创建返回的字符串,“检查未签名”。

用户可以选择几个原因,因此根据选择,我需要格式为“x,y和z”或“y和z”或“z”的句子结构。 (例如:“支票未签署,支票已过期,支票为第三方支票。”)

似乎需要从选择中创建一个数组,选择计数,然后用“If then”语句来创建句子,但我很难过。我可以计算所选项目,如果只选择了1项,我可以创建句子,但是复合句子让我感到困惑。

vba ms-word word-vba
3个回答
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)

从那时起,你可以用“和”替换最后一个逗号,你应该全部设置。


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

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
© www.soinside.com 2019 - 2024. All rights reserved.