Consulting

Results 1 to 4 of 4

Thread: Word UserForm with three checkboxes to insert text at cursor

  1. #1

    Word UserForm with three checkboxes to insert text at cursor

    I have some *very* basic familiarity with writing macros but have never created a UserForm. I'm trying to make a simple form in Word with three checkboxes -- say, Checkbox1, Checkbox2, and Checkbox3. You click the checkbox(es), click an "OK" button at bottom, and then, depending on what checkbox(es) you've checked, it inserts the sentence(s) at the cursor location -- say "This is the sentence for [Checkbox1]" -- followed by a new line.

    I think I get how the code should work conceptually: Each checkbox click event adds the sentence to a variable string(?), and then the OK button click event pastes the string. But I'm at a loss on how to write and execute it.

    Sorry for not coming with attempted code in hand -- I've strictly worked from recorded macros in the past and don't know where to start -- but any advice would be greatly appreciated. Thanks!

  2. #2
    UPDATE:

    I've written the code below, which more or lets lets me do what I was hoping to, for two clickboxes. I can keep this up for the third, fourth, etc. but would love any thoughts on whether there's a more elegant way to do so -- particularly with the various conditional statements. (I'll probably have 20 boxes in total.) Thanks again!

    Private Sub cmdAddToDocument_Click()
    Application.ScreenUpdating = False
    Dim strNewText As String
    Dim text1 As String
    Dim text2 As String
    text1 = "Random string of text."
    text2 = "Another random string of text."
    If cbx1 = True Then strNewText = text1
    If cbx2 = True Then strNewText = strNewText & vbNewLine & text2
    With ActiveDocument
        Selection.Text = strNewText
    End With
    Application.ScreenUpdating = True
    Unload Me
    End Sub
    Last edited by Aussiebear; 04-16-2023 at 03:32 PM. Reason: Reduced the whitespace

  3. #3
    That will work, though you might want to consider writing to content controls, especially if the document isn't simply a selection of consecutive texts.
    See https://www.gmayor.com/Userform.htm
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes
    http://www.gmayor.com

  4. #4
    Thanks! I will try that.

    One follow-up: As my code is currently written, if cbx1 isn't clicked but cbx2 is, then the string that gets pasted in leads with a new line. Is there a simple way to just do "If [first line of strNewText] = vbNewLine[?] Then [delete first line of strNewText]"?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •