Find all instances of a string, e.g., “a dog”, and insert *in tracked* a reference numeral, e.g., (102), immediately afterwards

  Kiến thức lập trình

I’d like a VBA macro in word to find all instances of a user-selected string in a document (e.g., “a dog”) and insert a corresponding user-selected reference numeral in parentheses (e.g., “(102)”) immediately following each string.

I have made a find-and-replace style macro but, in tracked changes, it shows as artificial revisions the deletion and re-insertion of the string itself, whereas I want only the inserted reference numeral to be shown in tracked as a revision.

I’d really appreciate any ideas as to how to show only the reference numerals in tracked, e.g., by adding loops in afterwards to accept specific string deletions and re-insertions, or by using an entirely different approach. I’m stumped.

Here is my inadequate finds-and-replace code, which successfully provides tracked reference numerals but does so at the expense of deleting and re-inserting the string itself (which is not what I’m after, since this shows up as artefact revisions in the Word document):

Sub RefNumerals()

Selection.Find.ClearFormatting
feature = InputBox("Type in claim feature:")
refnum = InputBox("Type in reference numeral")
With Selection.Find
.Text = feature
.Replacement.Text = feature & " (" & refnum & ")"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
End With

Selection.Find.Execute Replace:=wdReplaceAll
End Sub

New contributor

cjrc is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT