Word-Fu: Visual Basic Macro for All Cross References

I was working on a report for a customer this morning and I wrote a macro that saved me a lot of tedious effort. I want to have a table that looks like this:

Goals and Risks

Notice the gray shading. That indicates that those are dynamic Cross References (Insert → Cross References"). If I change the heading text, or the numbering, or anything else in the document related to that heading, these cross references will all update, also. But I don’t want to go to the menu and manually enter them all. This macro, if you run it, will insert a long list of all the cross references to headings in your document (wherever your cursor happens to be). I ran it on my document and got something like this:

All cross references

Then all I have to do is select all that text, and go to Table → Convert" → Text to Table. It will convert it to a nice table that I can then copy, paste, reformat, etc.

Here’s the macro. I wrote it for Microsoft Word 2004 for Macintosh. I expect it probably works on Microsoft Word for Windows, too. Add it to a word document, and you’re off to the races. Just remember what Djikstra said about learning BASIC.

Sub MakeXRefs()
'
' Get all headings and make cross references to their number and title
' Paco Hope <blog@filter.paco.to>
'
headingArray = ActiveDocument.GetCrossReferenceItems(wdRefTypeHeading)
For i = 1 To UBound(headingArray)
Selection.InsertCrossReference ReferenceType:="Heading", ReferenceKind:= _
wdNumberRelativeContext, ReferenceItem:=i, InsertAsHyperlink:=True, _
IncludePosition:=False`

  `Selection.TypeText (" ")`

  `Selection.InsertCrossReference ReferenceType:="Heading", ReferenceKind:= _
wdContentText, ReferenceItem:=i, InsertAsHyperlink:=True, _
IncludePosition:=False`

  `Selection.TypeParagraph
Next i
End Sub

“It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.” Edsger Dijkstra (Dutch Computer Scientist. Turing Award in 1972. 1930-2002)

Comments aren't enabled for this post.