Add Method (Variables Collection) Example
This example adds a variable named "Temp
" to the active document and then inserts a DOCVARIABLE field to display the value in the Temp
variable.
With ActiveDocument
.Variables.Add Name:="Temp", Value:="12"
.Fields.Add Range:=Selection.Range, _
Type:=wdFieldDocVariable, Text:="Temp"
End With
ActiveDocument.ActiveWindow.View.ShowFieldCodes = False
This example sets the value of the Blue
variable to 6. If this variable doesn't already exist, the example adds it to the document and sets it to 6.
For Each aVar In ActiveDocument.Variables
If aVar.Name = "Blue" Then num = aVar.Index
Next aVar
If num = 0 Then
ActiveDocument.Variables.Add Name:="Blue", Value:=6
Else
ActiveDocument.Variables(num).Value = 6
End If
This example stores the user name (from the Options dialog box) in the template attached to the active document.
ScreenUpdating = False
With ActiveDocument.AttachedTemplate.OpenAsDocument
.Variables.Add Name:="UserName", Value:= Application.UserName
.Close SaveChanges:=wdSaveChanges
End With