Tag Archives: Form Field

VBA – Word – Update/Fill-in Document Form Fields

Have you ever needed to fill-in or update the form fields of a Word Document from say Access, Excel, … Below is a simple example of how you can do this. In it I demonstrate how to populate a textbox, as well as show you how you can check/uncheck a checkbox.

'---------------------------------------------------------------------------------------
' Procedure : UpdateDoc
' Author    : CARDA Consultants Inc.
' Website   : http://www.cardaconsultants.com
' Purpose   : Update/Fill-in a Word document's form fields
' Copyright : The following may be altered and reused as you wish so long as the
'             copyright notice is left unchanged (including Author, Website and
'             Copyright).  It may not be sold/resold or reposted on other sites (links
'             back to this site are allowed).
'
' Revision History:
' Rev       Date(yyyy/mm/dd)        Description
' **************************************************************************************
' 1         2010-Sep-17                 Initial Release
'---------------------------------------------------------------------------------------
Sub UpdateDoc()
'Requires a reference to the Word object library
Dim oApp        As Object 'Word.Application
Dim oDoc        As Object 'Word.Document
Dim sDocName    As String

On Error Resume Next
    Set oApp = GetObject(, "Word.Application") 'See if word is already running
    If Err.Number <> 0 Then     'Word isn't running so start it
        Set oApp = CreateObject("Word.Application")
    End If

On Error GoTo Error_Handler_Exit
    sDocName = "YourWordDocToOpenFullPathAndExtension"
    Set oDoc = oApp.Documents.Open(sDocName)
    oApp.Visible = True
    
    oDoc.FormFields("TextboxName").Result = "NewValue"      'Textbox
    oDoc.FormFields("CheckboxName").CheckBox.Value = True   'Checkbox

Error_Handler_Exit:
    On Error Resume Next
    oDoc.Close True
    oApp.Quit
    Set oDoc = Nothing
    Set oApp = Nothing
    Exit Sub

Error_Handler:
    If Err.Number = 5174 Then
        MsgBox "The specified file '" & sDocName & "' could not be found.", _
               vbCritical
    Else
        MsgBox "The following error has occurred." & vbCrLf & vbCrLf & _
               "Error Number: " & Err.Number & vbCrLf & _
               "Error Source: UpdateDoc" & vbCrLf & _
               "Error Description: " & Err.Description, _
               vbCritical, "An Error has Occurred!"
    End If
    Resume Error_Handler_Exit
End Sub