[code]
' Module/Form level variable
Private objWord as Word.Application
Set objWord = CreateObject or Getobject
' Get your document as active document
SetDocVariable "Customername", strValue
UpdateFieldsAndPrintDocument
objWord.ActiveFocument.Close false
objWord.Quit false
Set objWord = Nothing
End Sub
'========================================================
Public Sub UpdateFieldsAndPrintDocument(Optional strCopies = "1")
'*****
'* Update fields with DOCVARIABLES
'*****
Dim lngIndex As Long, _
strDescription As String
With objWord.ActiveDocument.Fields
lngIndex = .Update
If lngIndex > 0 Then
strDescription = .Item(lngIndex).Code.Text & vbCrLf & _
"Fields Update error"
MsgBox strDescription, vbInformation, _
objWord.ActiveDocument.Name
End If
End With
'*****
'* Print Document
'*****
Application.PrintOut FileName:="", _
Range:=wdPrintAllDocument, Item:= _
wdPrintDocumentContent, _
Copies:=strCopies, _
Pages:="", _
PageType:=wdPrintAllPages, _
Collate:=True, _
Background:=False, _
PrintToFile:=False
End Sub
Public Sub SetDocVariableFmt(ByVal strVariableName As String, _
ByVal strValue As Variant, _
ByVal strFormat As String)
'*****
'* format the value before doing Replace unless
'* there is no value.
'*****
Dim strNew
If Len(Trim(strValue)) = 0 Then ' No value
strNew = " "
Else
strNew = Format(strValue, strFormat)
End If
SetDocVariable strVariableName, strNew
End Sub
Public Sub SetDocVariable(ByVal strVariableName As String, _
ByVal strValue As String)
Dim strDescription As String, _
strWValue As String
If Len(strValue) = 0 Then
strWValue = Space(1) ' Can not be zero length string
Else
strWValue = strValue
End If
'*****
'* Place the value into the indicated Variable.
'* Variables is a "Collection".
'*****
On Error Resume Next
objWord.ActiveDocument.Variables(strVariableName) = strWValue
strDescription = Err.Description
On Error GoTo 0
If Len(strDescription) > 0 Then
strDescription = strDescription & vbCrLf & _
"DocVariable=" & strVariableName & " not defined."
MsgBox strDescription
objWord.ActiveDocument.Variables.Add strVariableName, _
strWValue
End If
End Sub