Document Variables

Document variables are string variables that can be saved into documents or templates.
The Document object has a Variables property that returns a Variables collection containing all variables associated with that document.
Using document variables provides you with a way of saving custom information without actually putting it on the document or using a custom property.


Creating Document Variables

This line of code will create a new variable called "Variable_1" with its string value containing the text "some text".

ActiveDocument.Variables.Add Name:="Variable_1" 
                             Value:="some text"

This line of code is equivalent but with a variable assigned to the Variables collection

Dim objVariablesCol As Variables 

Set objVariablesCol = ActiveDocument.Variables
objVariablesCol.Add Name:="Variable_1"
                    Value:=10

Retrieving the Value from a Variable

This line of code will return the string value assigned to the variable called "Variable_1".

Dim sValue As String 
sValue = ActiveDocument.Variables("Variable_1").Value

Saving Blank Values

If you save an empty string in your document variables it will be removed automatically.
KB306281



Determining if a Variable exists

If you try to add a variable with the same name as an existing one you will get an error.
There is no Exists property so you have to cycle through them all to determine if the name already exists

Dim objVariable As Variant 
For Each objVariable AIn ActiveDocument.Variables

Next objVariable

Instead of looping through the entire collection which could take a while you could use a dedicated function instead.
Remember you should never use the "On Error Resume Next" statement so you need to catch any errors.

If DoesVariable_Exists("Variable_1", ByRef sMyValue) Then 
End If

Public Function DoesVariable_Exist(byVal sVariableName As String, _
                             ByRef sReturn As String) As Boolean

   On Error GoTo AnError
   sReturn = ActiveDocument.Variables(sVariableName).Value
   DoesVariable_Exist = True
   Exit Function

AnError:
   sReturn = "doesn't exist"
   DoesVariableExist = False
End Function

Deleting a Document Variable

This line of code will delete the document variable called "Variable_2" from the active document

ActiveDocument.Variables("Variable_2").Delete 

DocVariable Field

Once a document variable has been added the value can be displayed using the DocVariable field.
Document variables can be added to document using the DOCVariable field



© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext