Excel to Word

< Back to home

< Back to development tips

Edit word documents from Excel.  This code is really cool, it opens up word document My Form.docx from Excel and populates all its content controls with their ContentControl numbers.  Now getting these numbers you can quickly write code to insert specific data into these controls. (see bottom of this page for examples of configuring content controls in Word)

VBA code to find control numbers

First run this code to determine the content control numbers of the word document. Now getting these numbers you can quickly write code to insert specific data into these controls.

Public Sub populateForm()
    Dim wordApp As Word.Application
    Dim wDoc As Word.Document
    Dim i As Integer
 
    Set wordApp = CreateObject("word.application")
    Set wDoc = wordApp.Documents.Open("C:\My Form.docx")
    wordApp.Visible = True
    totalFields = wDoc.ContentControls.Count
 
     For i = 1 To totalFields
        If wDoc.ContentControls(i).Type = wdContentControlCheckBox Then
            wDoc.ContentControls(i).Checked = True
        Else
            wDoc.ContentControls(i).Range.Text = i
        End If
    Next i
   
    wordApp.Documents.Close
    wordApp.Quit
End Sub

 

Procedure to create form fields

Step 1: 

Create a word document.  This will be your template form.

Step 2: 

Enable the developer tab.

Step 3:

Add required content controls.  These act as containers which the excel code can easily populate.  Below are examples of adding two types of content controls.

Example 1 - Adding text field

Word - How to add a rich text field

 

Example 2 - Adding check box

Word - How to add a checkbox control

 

 

 

< Back to home

< Back to development tips