Reputation: 1798
I have a Word VBA macro that extracts the first sentence of each paragraph from a source document and puts the extracted text into a temporary summary document. It's an aid to better writing.
In operation, I write something in the source document, run the macro, and see the first sentences in the temporary summary document. Using set docsummary = Documents.Add
, the temporary document always has a filename of the form DocumentNN
, where NN increases by one each time I run the macro.
I want to use set docsummary = Documents("some temp name")
to fetch and reuse the same temporary document over and over again. The problem is that I can't seem to set the name of the temp document without saving it to disk (and I don't want to do that because the macro should run on my Windows machine and on a Mac, and I don't know of a temp filepath on a Mac.)
Is there any way to set a recognizable property on the new temp document (a name, an ID, or whatever) so that I can search for that value to find the temp doc when my macro runs again?
I suppose that I might take the given name and save it in a global variable (if that's possible) for the next time the macro runs. Or I could insert some special text inside the temp doc and search for that special text later to find the doc in the Documents collection.
But I'm wondering if there's a doc property that I don't know about that I can use directly. Thank you.
Upvotes: 1
Views: 545
Reputation: 25693
Using a global variable is a possibility, but those can "get lost" if something "hiccups" in the VBA editor or project. For that reason it might make more sense to check a document for something, at least as a back-up in case the global variable gets reset to Nothing
.
In principal you can create your own CustomDocumentProperty
. Or you could use a document Variable
. These aren't things that can be picked up directly from the Document
object, but they can be queried.
For example
Dim docSummary as Document
Set docSummary = Documents.Add
docSummary.Variables("DocName") = "some temp name"
Then later, to pick the document back up, in some code that needs to work with the temporary document
Dim docSummary as Document
Set docSummary = RetrieveTempDoc()
And the function checks for the Variable
(or CustomDocumentProperty
or whatever you choose to use as an identifier):
Function RetrieveTempDoc() As Document
Dim doc as Document
For Each doc in Documents
If doc.Variables("DocName") = "some temp name" Then
Exit For
End If
Next
Set RetrieveTempDoc = doc
End Function
Upvotes: 2