Search code examples
vbalistms-wordcomboboxuserform

Word 2013- VBA- How To Add Punctuation to Results From A User Form List Box?


I have a user form with list box (multi selection) with four entries.

enter image description here

The following code builds the string:

Dim myArray() As String
'Use Split function to return a zero based one dimensional array.
    myArray = Split("text 1|" _
            & "text 2|" _
            & "text 3|" _
            & "text 4", "|")
  'Use .List method to populate listbox.
  ListBox1.List = myArray
  'Use the .ColumnWidth property to set column widths.  0 results in a hidden column.
  ListBox1.ColumnWidths = "1"
lbl_Exit:
  Exit Sub

The following code below successfully inserts any combination of the four selected entries with a , and space in between each entry including a . at the end i.e. text 1, . or text 1, text 2, text 3, . or text 1, text 2, text 3, text 4, . into a content control.

Dim SelectedTexts As String
Dim index As Long
    For index = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(index) Then
            'Adds comma after every entry
            SelectedTexts = SelectedTexts & ListBox1.List(index) & ", "
        End If
    Next
    'Adds period to the end
    ActiveDocument.SelectContentControlsByTitle("test").Item(1).Range.Text = Mid(SelectedTexts, 1) _
    & "."
Unload Me

lbl_Exit:
  Exit Sub
Me.Repaint
Me.Hide

I am trying to accomplish two things:

  1. I only want a . after the last entry i.e. text 1. NOT text 1, .
  2. I want there to be an and before the last result i.e. text 1 and text 2. or text 1, text 2 and text 3. or text 1, text 2 and text 4.

Solution

  • Once your string is built, you need to manipulate it into the form you require. Here is the logic to do this:

    Private Sub Test()
       Dim SelectedTexts As String
       Dim index As Long
       
       For index = 0 To ListBox1.ListCount - 1
          If ListBox1.Selected(index) Then
             SelectedTexts = SelectedTexts & ListBox1.List(index) & ", "
          End If
       Next
    
       SelectedTexts = Mid(SelectedTexts, 1, Len(SelectedTexts) - 2) & "."
       index = InStrRev(SelectedTexts, ",")
       If index > 0 Then SelectedTexts = Left(SelectedTexts, index - 1) & " and " & Right(SelectedTexts, Len(SelectedTexts) - index - 1)
    
       ActiveDocument.SelectContentControlsByTitle("test").Item(1).Range.Text = SelectedTexts
    End Sub