Autofilling with Word

Posted by The Inspector on October 10th, 2007 filed in computers

Open your Word template and replace all the highlighted areas with Text Form Fields from the Forms Toolbar.
(VIEW –> TOOLBARS –> FORMS)

After adding the form fields you can re-save and close the Word doc. Next open your Excel file containing the list of company names and click ALT + F11 to bring up the VBA editor. Next click INSERT –> MODULE and copy and past the code below into the blank module. Re-Save the Excel workbook and then run the macro called “FillForm”

After running the macro you will be prompted to select the Word template file using a dialogue box. The newly created individual Word files will be saved using the company name as the filename and they will be saved to the same path as the template doc. Just make sure the company name does not contain any special characters such as the backslash / since Windows will not allow special characters in the filename.

(The code assumes that the first record is on row 1 and there are no blank rows of data)

Public Sub FillForm()

Dim objWord As Object
Set objWord = CreateObject(”Word.Application”)

With objWord.Application.Dialogs(wdDialogFileOpen)
.Name = “*”
If .Display = -1 Then
vPath = objWord.Options.DefaultFilePath(wdCurrentFolderPath) & “\”
vFilePath = vPath & .Name
End If
End With

objWord.Documents.Open (vFilePath)

For i = 1 To Cells(Rows.Count, “A”).End(xlUp).Row

vCompany = Range(”A” & i).Value

For Each vField In objWord.ActiveDocument.Fields

objWord.ActiveDocument.FormFields(vField.Index).Result = vCompany

Next vField

objWord.ActiveDocument.SaveAs (vPath & vCompany & “.doc”)

Next i

objWord.ActiveDocument.Close
objWord.Quit
Set objWord = Nothing

End Sub

Leave a Comment