Search code examples
vbaoffice-2010

In VBA, are template global variables accessible by documents and sub-templates?


I am writing a template in Word 2010 which is based upon another template, both of which contain considerable amounts of VBA code. I have referenced the original template to access its modules. Are global variables in the original template also accessible this way? If so, is there a coding standard to access them, such as:

TheTemplate.VariableName

or can they just be accessed by name:

VariableName

Solution

  • Each template is a closed object. None of the variables global to it a template's modules will be accessible or visible to any other template that is currently loaded.

    What you can do is add public properties to a document object. Add them to the "ThisDocument" class module every document has, for example a string property like this:

    Public Property Get Foo() As String
      Foo = "Any value"
    End Property
    

    Now you can access that property from anywhere, as it will be exposed by that Document object:

    MsgBox Application.Documents("appropriate document reference").Foo
    ' alerts "Any value"