Thursday, March 18, 2010

A Word macro for wordcount

I'm doing 500-word writing sessions; to do that, I need to know how many words there are in my file when I start, I need a quick way to get the current wordcount, and I need to know what my goal is.

So I came up with this macro. It's for Word 2003. When you run it, it generates a line like this:

Start 11609, current 12167, goal 12109

and the value for the current wordcount is a field code, so you can update it at any time by clicking on it and hitting F9. Yes, this would be unnecessary if I had the latest version of Word, which displays the wordcount in the status bar, but I don't have that. Also, that version of Word hides menu options from you more effectively than any previous version.

I thought the code for generating the field code was pretty arcane, but I got it by recording the action of adding a field code.

Sub WordCount()
' WordCount Macro
' This macro puts a line about wordcount into the current document.
' It puts the 'start' wordcount..the count you start with
' then the 'current', which is a NumWords field code that you can update with F9
' then it puts the 'goal, which is start + 500.
Dim Numwords As Integer
Dim Goalwords As Integer

'Ok, now populate Numwords with the value of the wordcount property
Numwords = ActiveDocument.BuiltInDocumentProperties(wdPropertyWords)
Goalwords = Numwords + 500

'The rest of this is just outputting text at the selection point
Selection.TypeText Text:="Start "
Selection.TypeText (Numwords)
Selection.TypeText Text:=", current "

'I generated the line below using a recording.
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
"NUMWORDS ", PreserveFormatting:=True
Selection.TypeText Text:=", goal "
Selection.TypeText (Goalwords)
End Sub

1 comment:

  1. Bonus! I learned that Visual Basic is almost unbearably obtuse. But I still got what I wanted.