Word VBA: Automating bookmark generation for individually numbered paragraphs

1. Problem summary

This is my first time writing VBA for Word. I have multiple documents; each one is larger than 100 pp., with a plaintext index according to paragraph number. I am writing a script to find and bookmark paragraphs according to the numbering format used in my documents, in order to hyperlink index entries and/or cross-reference the documents.

2. Details

Numbering format is {##-###.} with chapter number before the hyphen and paragraph sequence number after. The original numbering does not contain leading zeroes.

I included a font color change in the script so that any paragraph numbers not captured as bookmarks will immediately stand out.

Where I am stuck

  • Current script matches the expression {##-###.} anywhere in the document; this is a problem because e.g. tables and figures are numbered using the same format as paragraphs. I need to somehow match this expression only with strings located at the start of a paragraph.
  • Current script uses the Bookmarks.Exists method to check for a bookmark of the same name before creating one. I would like to check as well for a bookmark at the same location as Selection.Start, but have not yet learned how.

3. Script

' Variables:
' pNum: verbatim result of the search expression
' arrPNum: array containing padded two-digit chapter at (0) and padded three-digit paragraph at (1)
' CleanPNum: chapter and paragraph reformatted into bookmark name
Sub makeBookmarks() Selection.Find.ClearFormatting With Selection.Find .Text = "[0-9]{1,2}-[0-9]{1,3}." .Replacement.Text = "" .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchByte = False .MatchAllWordForms = False .MatchSoundsLike = False .MatchWildcards = True End With For Each para In ActiveDocument.Paragraphs Selection.Find.Execute pNum = Selection If pNum <> "" Then arrPNum = Split(Left(pNum, Len(pNum) - 1), "-") CleanPNum = "para_" & Format$(arrPNum(0), "00") & "_" & Format$(arrPNum(1), "000") End If If ActiveDocument.Bookmarks.Exists(CStr(CleanPNum)) = True Then Selection.MoveRight Unit:=wdWord, Count:=1 Else Selection.Font.Color = 15132391 Selection.MoveLeft Unit:=wdCharacter, Count:=1 With ActiveDocument.Bookmarks .Add Range:=Selection.Range, Name:=CStr(CleanPNum) .DefaultSorting = wdSortByName .ShowHidden = False Selection.MoveRight Unit:=wdWord, Count:=1 End With End If Next
End Sub
1 Reset to default

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like