Hello,
I'm trying to write a simple macro that determines if a Section number within the document's text has a field code. In other words, did the author use Microsoft Word's "cross-reference" feature. For example, "Please see Section 1 for more details." Does the "1" have a field code? If it does then turn the font blue. If it doesn't then turn the font red and add a comment.
I tried to mimic this application based off of a similar question, where I was looking for "Table n". However, it seems there is something unique about "Section n" vs "Table n". That solution is located
here.
I believe the format is the word "Section" + non-breaking space + number. Therefore, my search string I have tried was:
aRng.Find.Text = "Section?[0-9.]{1,}"
However, this isn't working. It finds the "Section n" if Word's cross-reference isn't used, but it misses the properly formatted one that uses Word's cross reference feature. My full code is below. I am attaching a simple Word file to illustrate the issue. The first paragraph has "Section 2" and was properly formatted with Word's cross-reference feature. Therefore, the font for "2" should be turned blue. The third paragraph has "Section 1.1", which was not properly formatted. Therefore, its font should be turned red and a comment added.
Thank for you in advance for any assistance!
Roy
Code:
Sub myMacro()
Dim aRng As Range
Set aRng = ActiveDocument.Range
With aRng.Find
.ClearFormatting
.Text = "Section^s[0-9.]{1,}"
.MatchWildcards = True
Do While .Execute ' Loop until Word can no longer find the search string
aRng.MoveStart Unit:=1, Count:=8 'wdCharacter = 1
aRng.MoveEnd Unit:=1, Count:=1
If aRng.Fields.Count > 0 Then 'there is a field
If InStr(1, aRng.Fields(1).Code.Text, "_Ref") > 0 And aRng.Font.Color <> vbBlue Then
aRng.Font.Color = vbBlue
End If
Else
aRng.Font.Color = vbRed
ActiveDocument.Comments.Add Range:=aRng, Text:="Missing cross-reference field code"
End If ''
aRng.Collapse Direction:=0 'wdCollapseEnd
Loop
End With
End Sub