Generate Word Documents (in Excel VBA) from a series of Document Templates

后端 未结 4 1024
闹比i
闹比i 2020-11-30 21:26

Hey all. I\'ll try to make this brief and simple. :)

I have

  1. 40 or so boilerplate word documents with a series of fields (Name, address
4条回答
  •  甜味超标
    2020-11-30 22:07

    http://www.computorcompanion.com/LPMArticle.asp?ID=224 Describes the use of Word bookmarks

    A section of text in a document can be bookmarked, and given a variable name. Using VBA, this variable can be accessed and the content in the document can be replaced with alternate content. This is a solution to having placeholders such as Name and Address in the document.

    Furthermore, using bookmarks, documents can be modified to reference bookmarked text. If a name appears several times throughout a document, the first instance can be bookmarked, and additional instances can reference the bookmark. Now when the first instance is programatically changed, all other instances of the variable throughout the document are also automatically changed.

    Now all that's needed is to update all the documents by bookmarking the placeholder text and using a consistent naming convention throughout the documents, then iterate through each documents replacing the bookmark if it exists:

    document.Bookmarks("myBookmark").Range.Text = "Inserted Text"
    

    I can probably solve the problem of variables that don't appear in a given document using the on error resume next clause before attempting each replacement.

    Thanks to Doug Glancy for mentioning the existance of bookmarks in his comment. I had no knowledge of their existence beforehand. I will keep this topic posted on whether this solution suffices.

提交回复
热议问题