Add Method (Variables Collection)

Applies To

Variables collection object.

Description

Adds a variable to a document.

Syntax

expression.Add(Name, Value)

expression Required. An expression that returns a Variables object.

Name Required String. The name of the document variable.

Value Optional Variant. The value for the document variable.

Remarks

Document variables are invisible to the user unless a DOCVARIABLE field is inserted with the appropriate variable name. If you try to add a variable with a name that already exists in the Variables collection, an error occurs. To avoid this error, you can enumerate the collection before adding a new variable to it.

See Also

Variables collection object.

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
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