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

JFr*_*nch 1 vba ms-word word-vba

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

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

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

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

Dav*_*ens 12

我有这个函数,它从列表框中返回一个选定项目的数组.我已从原来的答案更新为返回分隔字符串而不是所选项目数组:

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
Run Code Online (Sandbox Code Playgroud)

你可以通过分配一个数组来调用它:

Dim mySentence as String
mySentence = GetSelectedItems(MyUserForm.MyListBox)
Run Code Online (Sandbox Code Playgroud)

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

  • 精彩!我建议将`lBox As MSForms.ListBox`更改为`lBox As Object`以避免丢失库错误,但我还必须将`tmpArray(selCount)= lBox.List(i)`更改为`tmpArray(selCount) = lBox.ItemData(i)`,因为我在该行上获得了无效的属性错误.否则,工作得很漂亮!这让它在Access 2010上为我工作. (2认同)