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".
This line of code is equivalent but with a variable assigned to the Variables collection
Dim objVariablesCol As Variables
Set objVariablesCol = ActiveDocument.Variables
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.
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
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
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
sReturn = "doesn't exist"
DoesVariableExist = False
Deleting a Document Variable
This line of code will delete the document variable called "Variable_2" from the active document
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
© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext