Search code examples
vbams-wordword-2016

Populate MS-Word ContentControl Text Boxes from UserForm TextBoxes with same name/tag?


I have created a Visual Basic for Applications program in Microsoft Word (2016, 64bit, Windows 10)

It consists of a UserForm with about 30 TextBoxes and a submit button. Each TextBox has a unique name and tag.

I also have the same number of ContentControl text boxes in the word document, each of them have the same title and tag as its corresponding UserForm TextBox.

What I'm after is a better way to populate the document text boxes from the UserForm TextBoxes when the user clicks submit.

I currently am doing this by typing 3 lines of code for each TextBox, but this is tedious. I copy and paste the 3 lines of code each time but must edit a small part of each line every time.

I thought about using a loop, as shown in the code below, where I use a variable x to copy the TextBox across by name, but I'm unsure how to proceed.

Dim doc As Document
Dim ccs As ContentControls
Dim cc As ContentControl
Set doc = ActiveDocument

For … 
' Somehow find each text box, put the name of one into variable x then

    Set ccs = doc.SelectContentControlsByTag(x)
    Set cc = ccs(1)
    cc.Range.Text = x.Text

Next

Thank you in advance!


Solution

  • All the TextBoxes are stored in a class of Shapes, which you can access like this:

    Sub Test()
    Dim shape As Shape
    Dim str As String
    
    For Each shape In ActiveDocument.Shapes
        str = "My name is " & shape.Name
        str = str & " My EditID is " & shape.EditID
        shape.TextFrame.TextRange.Text = str
    Next
    End Sub
    

    You need to name your textboxes so that you can identify them as textboxes, then you can check to see if they are textboxes before you write to them.