jkramer
jkramer

Reputation: 13

Word VBA: Sharing variables between documents

I feel like this should be obvious, I'm just not finding the answer anywhere.

I have a Word document with several Public variables declared and defined in a variety of procedures. One procedure opens another Word document, which has a form that loads on open. For the life of me I cannot get that form in the second document to use values from the original document's variables. Am I misunderstanding the nature of Public variables? Everything I've found seems to indicate that those values should be visible to the newly opened document.

So to open the second document, I'm using the code below (some of it is declared and set elsewhere, but I think this is the relevant stuff:

Public iMarker as boolean

Sub OpenDoc()
   If check_ExA.Value = True Then 'a checkbox on a userform
   docName = docsPath & "/" & "seconddocumentpath.docm"
   iMarker = True
   formAddDocs.Hide
   Set addDoc = Documents.Open(docName)
End Sub

from there, the new document has a form that shows on Open, and in the initialization, I want it to be able to see if the iMarker variable is true, among some other strings, etc.

Private Sub UserForm_Initialize()

If iMarker = True Then
  'do some other stuff
End If

End Sub

I tried changing that Initialize sub to public and that did nothing. It won't see that iMarker is true when the second document opens. Any suggestions?

Upvotes: 1

Views: 729

Answers (1)

user3598756
user3598756

Reputation: 29421

To make a public variable of doc01 ("source doc") available to doc02 ("target doc") document, go like follows:

  • open the "source doc"

  • open the "target doc"

  • click Tools-> References

  • from Available References listbox of the References dialog box click the "Project" of the "source doc"

    You can recognize it from the path appearing near the dialog box bottom

    Otherwise

    • close Reference dialog box
    • go to "source doc" and rename its project (Tools->project properties, edit "project name" textbox and click "OK") with a meaningful name (say "MainProject")
    • go back to "target doc" project
    • open References dialog box and now from Available References listbox click the "MainProject" reference
  • Save and close target doc

Upvotes: 1

Related Questions