Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Variables Collection Object (Word)

A collection of Variable objects that represent the variables added to a document or template. Document variables are used to preserve macro settings in between macro sessions.

Use the Variables property to return the Variables collection. The following example displays the number of variables in the document named "Sales.doc."

MsgBox Documents("Sales.doc").Variables.Count & " variables"

Use the Add method to add a variable to a document. The following example adds a document variable named "Temp" with a value of 12 to the active document.

ActiveDocument.Variables.Add Name:="Temp", Value:="12"

If you try to add a document 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 any new variables. If the Blue document variable already exists in the active document, the following example sets its value to 6. If this variable doesn't already exist, this 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

Use Variables(Index), where Index is the document variable name or the index number, to return a single Variable object. The following example displays the value of the Temp document variable in the active document.

MsgBox ActiveDocument.Variables("Temp").Value

The index number represents the position of the document variable in the Variables collection. The first variable added to the Variables collection is index number 1; the second variable added to the collection is index number 2, and so on. The following example displays the name of the first document variable in the active document.

MsgBox ActiveDocument.Variables(1).Name

To add a variable to a template, open the template as a document by using the OpenAsDocument method. The following 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
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.