PDA

View Full Version : Word UserForm with three checkboxes to insert text at cursor



John1984
03-01-2022, 09:48 AM
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!

John1984
03-01-2022, 02:29 PM
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

gmayor
03-01-2022, 09:54 PM
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

John1984
03-02-2022, 09:00 AM
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]"?