View Single Post
 
Old 07-23-2021, 05:50 PM
Guessed's Avatar
Guessed Guessed is offline Windows 10 Office 2016
Expert
 
Join Date: Mar 2010
Location: Canberra/Melbourne Australia
Posts: 3,980
Guessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant future
Default

This appears to work with your sample docs. I would recommend testing it on A COPY of your real documents.
Code:
Sub RestrictXRefs()
  Dim aFld As Field, aRngXRef As Range, sWord As String, aRngAnchor As Range, sBkmk As String
  Dim arrCode() As String, aRng As Range
  For Each aFld In ActiveDocument.Fields
    If aFld.Type = wdFieldRef Then
      Set aRngXRef = aFld.Result
      sWord = LCase(Trim(aRngXRef.Words(1)))
      If sWord = "table" Or sWord = "figure" Then
        arrCode = Split(Trim(aFld.Code), " ")
        sBkmk = arrCode(1)
        If ActiveDocument.Bookmarks.Exists(sBkmk) Then
          Set aRngAnchor = ActiveDocument.Bookmarks(sBkmk).Range
          aRngAnchor.MoveStart Unit:=wdCharacter, Count:=Len(sWord) + 1
          ActiveDocument.Bookmarks.Add Name:=sBkmk, Range:=aRngAnchor
          aFld.Update
          aFld.Select
          Selection.Range.InsertBefore sWord & " ("
          Selection.Range.InsertAfter ")"
        End If
      End If
    End If
  Next aFld
End Sub
I'm happy to accept criticism and corrections to the Selection object I used. I was having trouble with the Range object insertbefore and insertafter (kept going inside the field result) so I took the unfortunate step of using Selection to get around that issue. This won't hurt your functionality but isn't the way I would prefer to do it.
__________________
Andrew Lockton
Chrysalis Design, Melbourne Australia
Reply With Quote