excelvba

List all words from a cell as a list in a ComboBox (userform)


I have cells with a sentence in each (text without line breaks). Now, when an existing Userform is opened, I would like each word of the text in the cell (in the last row) to be listed in a Combobox-List (dropdown). Each Word of the sentence is under another, so that I can choose one. Is this possible? Optionbuttons would also be possible: So if there are 10 words in the cell for example; 10 OptionButtons with the referring words would appear.

I know how to assign values from a Range to a ComboBox.List, but not what I need as described above.

Edit: This is the code I use:

Private Sub UserForm_Activate()
    FillComboBox ActiveSheet.Cells(Rows.Count, 1).End(xlUp)
End Sub

Sub FillComboBox(sentence As String)
    ' Split into words, get rid of "," and "."
    Dim words() As String, i As Long
    words = Split(Replace(Replace(sentence, ",", " "), ".", " "), " ")
    
    Me.ComboBox_VerseWords.Clear
    For i = LBound(words) To UBound(words)
        If words(i) <> "" Then
            Me.ComboBox_VerseWords.AddItem words(i)
        End If
    Next
End Sub

Solution

  • Use the Split-function to get a list of words from your sentence. Loop over the words and use the Combobox AddItem method to add these words to the combobox.

    Put the following code into the code behind module of the Userform. Adapt to your needs.

    Private Sub UserForm_Activate()
        FillComboBox ActiveSheet.Cells(1, 1)
    End Sub
    
    Sub FillComboBox(sentence As String)
        ' Split into words, get rid of "," and "." 
        Dim words() As String, i As Long
        words = Split(Replace(Replace(sentence, ",", " "), ".", " "), " ")
        
        Me.ComboBox1.Clear
        For i = LBound(words) To UBound(words)
            If words(i) <> "" Then
                Me.ComboBox1.AddItem words(i)
            End If
        Next
    End Sub
    
    

    The example shows that the combo box is filled at the Activate-Event of the form, but you can call FillComboBox at any time you need it and feed it with whatever sentence you want to deal with.

    enter image description here

    Using OptionButtons is possible but much more complicated: