Search code examples
excelvbauserform

How can I add a separator in between words in a userform, except the last word?


I have a code that fills a textbox with the captions from selected checkboxes automatically. Here is the code:

If PITCHSTYLESPOPUP.CheckBox1 = True Then Mark1.NEWPITCHSTYLETEXTBOX.Value = Mark1.NEWPITCHSTYLETEXTBOX.Value & PITCHSTYLESPOPUP.CheckBox1.Caption & " - "
If PITCHSTYLESPOPUP.CheckBox2 = True Then Mark1.NEWPITCHSTYLETEXTBOX.Value = Mark1.NEWPITCHSTYLETEXTBOX.Value & PITCHSTYLESPOPUP.CheckBox2.Caption & " - "
If PITCHSTYLESPOPUP.CheckBox3 = True Then Mark1.NEWPITCHSTYLETEXTBOX.Value = Mark1.NEWPITCHSTYLETEXTBOX.Value & PITCHSTYLESPOPUP.CheckBox3.Caption & " - "

My issue is that I want to put separators in between the captions without putting a separator after the last one. For instance, leaving the " - " if there is nothing coming after it.


Solution

  • As a "helper" method:

    Sub Tester()
        '...
        '...
        AddCaptionsIfChecked Mark1.NEWPITCHSTYLETEXTBOX, PITCHSTYLESPOPUP.CheckBox1, _
                            PITCHSTYLESPOPUP.CheckBox2, PITCHSTYLESPOPUP.CheckBox3
                               
    End Sub
    
    'add the caption from each checked checkbox in `checks` to textbox `txtBox`
    Sub AddCaptionsIfChecked(txtBox As Object, ParamArray checks() As Variant)
        Dim cb
        For Each cb In checks
            If cb.Value Then
                txtBox.Value = txtBox.Value & IIf(Len(txtBox.Value) > 0, " - ", "") & cb.Caption
            End If
        Next cb
    End Sub