如何使用Word VBA将多选列表框值返回到句子中? [英] How do I return multi select listbox values into a sentence using Word VBA?

查看:232
本文介绍了如何使用Word VBA将多选列表框值返回到句子中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've created a multi select listbox on a userform. There are 9 items in the listbox. How do I gather those selected items into a sentence?

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

The listbox contains reasons for returning a check. The items in the listbox are idenfiers or placeholders for a longer string, so the selection "unsigned", creates the returned string, "the check was not signed".

用户可以选择多种原因,因此根据选择,我需要格式为:"x,y和z"或"y和z"或"z"的句子结构. (例如:支票未签名,支票具有过期日期,并且支票是第三方支票.")

The user can select several reasons, so depending on the selections, I need sentence structure that formats as: "x, y, and z" OR "y and z" OR "z". (ex: "the check is not signed, the check is post-dated, and the check is a third-party check.")

似乎需要根据选择内容创建一个数组,对选择内容进行计数,然后使用"If then"语句创建该句子,但是我很困惑. 我可以计算选择的项目,如果只选择一项,则可以创建句子,但是复合句使我很困惑.

It seems as though an array needs to be created from the selections, the selections counted, then an "If then" statement to create the sentence, but I'm stumped. I can count the selected items, I can create the sentence if only 1 item is chosen, but the compound sentence stumps me.

推荐答案

我具有此功能,该功能可从列表框中返回选定项的数组.我已经从原始答案更新为返回定界字符串,而不是所选项目的数组:

I have this function which returns an array of selected items from a listbox. I have updated from my original answer to return a delimited string instead of an array of selected items:

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

您可以通过分配给数组来调用它:

You can call this by assigning to an array:

Dim mySentence as String
mySentence = GetSelectedItems(MyUserForm.MyListBox)

从那时起,您可以将 last 逗号替换为和",并且应该已经全部设置好.

From that point, you could just replace the last comma with a " and" and you should be all set.

这篇关于如何使用Word VBA将多选列表框值返回到句子中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆