Quick
Quick

Reputation: 43

Macro to field code

I currently have a Normal.dot macro that counts the amount of words in the current section:

Sub SectionWordCount()
  Dim SectionWordCount As String
  SectionWordCount = ActiveDocument.Sections _
  (Selection.Information(wdActiveEndSectionNumber)). _
    Range.ComputeStatistics(wdStatisticWords)
MsgBox "The current section has " & SectionWordCount & " words."
End Sub

Would it be possible to link this macro to a "field code" in my document? Or make this count appear in the document using any other form of VBA voodoo?

I'm using Word 2013 on Windows 8.

Thanks again, everyone.

Upvotes: 2

Views: 2240

Answers (1)

joeschwa
joeschwa

Reputation: 3175

Here's how to link your variable to a field code.

In your Word document, insert a DOCVARIABLE field inside the text. If I call this variable "wrdCount" the field code looks like this:

{DOCVARIABLE wrdCount \* MERGEFORMAT}

Then assign the value to your document in VBA and update the field code:

 ActiveDocument.Variables("wrdCount").Value = SectionWordCount
 ActiveDocument.Fields.Update

If you track the word count for multiple sections of the document, you will need a separate DOCVARIABLE for each section.

Upvotes: 2

Related Questions