Salı, Mart 01, 2011

DevBlog: Update All Fields in Word Documents - A blog about software development

DevBlog: Update All Fields in Word Documents - A blog about software development

Update All Fields in Word Documents

Automatically update every field element (e.G., Table of Contents, Document Fields, Computed fields, etc.) in a Microsoft Word Document in one motion.

In the business analysis, tech-lead part of my job, I tend to create Word documents that can be used in a "template" way. For example, if I have revision numbers, dates, company names, document titles, etc., I'll create document fields and place them in the document instead of the actual value. This way, if I want to recycle the document for a different situation, I only need to modify a few key fields and update the document.

However, Word doesn't give you a way to update all the fields at once. You have to highlight the entire document and then update the various components separately. This includes visiting each set of headers and footers if you happened to use a field like a document title in them.

So, to make life easier for me, I created this little macro that will visit everything in the document and update it. Here's the source code:

Sub UpdateAllFields() Dim oStory As Range Dim oField As Field   For Each oStory In ActiveDocument.StoryRanges     For Each oField In oStory.Fields       oField.Update     Next oField   Next oStory End Sub

Just copy this snippet into your base, Normal.dot. Then, tie the macro to a button on a command bar and you have a one click "Update All" widget!

The next time you want to change something about a document, all you have to do is choose "File Properties", change the field on the custom tab, return to the document and click your snazzy "Update All" button. Presto, new document with different titles, customer names and numbers! With this macro, you'll be cranking out documents faster than anyone . . .

Hiç yorum yok: