Class Variable (Word VBA)

The class Variable represents a variable stored as part of a document. Document variables are used to preserve macro settings in between macro sessions. The Variable object is a member of the Variables collection. The Variables collection includes all the document variables in a document or template.

Set

To use a Variable class variable it first needs to be instantiated, for example

Dim vrb as Variable
Set vrb = ActiveDocument.Variables(Index:=1)

The following procedures can be used to set variables of type Variable: Variables.Add, Variables.Item and Document.Variables

For Each

Here is an example of processing the Variable items in a collection.

Dim vrb As Variable
For Each vrb In ActiveDocument.Variables
	
Next vrb

Delete

Deletes the specified variable.

ActiveDocument.Variables(1).Delete

Index

Returns a Long that represents the ordinal position of a variable with in the collection of variables.

Set myVar = ActiveDocument.Variables.Add(Name:="Name", _ 
 Value:="Joe") 
num = myVar.Index

Name

Returns the name of the specified object.

Dim strName As String
strName = ActiveDocument.Variables(1).Name

Parent

Returns an object that represents the parent object of the specified Variable object.

Dim objParent As Object
Set objParent = ActiveDocument.Variables(1).Parent

Value

Returns or sets the value of a document variable.

ActiveDocument.Variables.Add Name:="Temp2", Value:="10" 
MsgBox ActiveDocument.Variables("Temp2").Value

Variables.Add

Returns a Variable object that represents a variable added to a document.

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.

Syntax : expression.Add (Name, Value)

With ActiveDocument 
 .Variables.Add Name:="Temp", Value:="12" 
 .Fields.Add Range:=Selection.Range, _ 
 Type:=wdFieldDocVariable, Text:="Temp" 
End With 
ActiveDocument.ActiveWindow.View.ShowFieldCodes = False

Arguments

The following argument is required

Name (String) - The name of the document variable.

The following argument is optional

Value (Variant) - The value for the document variable.

Variables.Count

Returns a Long that represents the number of variables in the collection.

Dim lngCount As Long
lngCount = ActiveDocument.Variables.Count

Variables.Item

Returns an individual Variable object in a collection.

Syntax : expression.Item (Index)

Index: The individual object to be returned. Can be a Long indicating the ordinal position or a String representing the name of the individual object.

Dim vrb As Variable
Set vrb = ActiveDocument.Variables(Index:=1)

Variables.Parent

Returns an object that represents the parent object of the specified Variables object.

Dim objParent As Object
Set objParent = ActiveDocument.Variables.Parent