Forum Discussion

R3d3mpt10n's avatar
R3d3mpt10n
Copper Contributor
Oct 28, 2019
Solved

Userform Listbox HELP

Greetings Everyone,    I need some HELP! Please bear with me if I ask too many questions, as I am fairly new to VBA.     Anyways,  I created a userform in Word 2016 to auto-populate a template bu...
  • Jay Freedman's avatar
    Oct 29, 2019

    R3d3mpt10n  The code to update the document should usually go into the Click procedure of the OK button (or whatever you've named it). In order to write that code, you need to know where in the document the text will go: it could be a bookmark, a content control, a legacy text form field, a particular table cell, etc. 

     

    As an example using a bookmark, your code can look like this:

     

    Private Sub btnOK_Click()
    Dim rg As Range

    Set rg = ActiveDocument.Bookmarks("TextHere").Range
    rg.Text = ListBox1.Value
    ActiveDocument.Bookmarks.Add "TextHere", rg

    ' any other actions that are needed

    Unload Me
    End Sub

     

    Private Sub UserForm_Initialize()
    With ListBox1
    .AddItem "VIA US MAIL ONLY"
    .AddItem "VIA Electronic Mail Only"
    .ListIndex = 0 ' guarantee that an entry is selected
    End With
    lbl_Exit:
    Exit Sub
    End Sub

     

    (The code for re-adding the bookmark after the inserted text has erased it comes from https://wordmvp.com/FAQs/MacrosVBA/InsertingTextAtBookmark.htm ).

     

    If the target in the document is one of the other things, or if you want help deciding which to use, reply to this thread.

Resources