PDA

View Full Version : [SOLVED:] Find text between two characters and create an endnote with that text



Automate
10-30-2017, 11:24 AM
Problem: I have to edit documents where people are required to cite sources like this:

George Washington liked apples. <Source #1> Thomas Jefferson prefers pears. <Source #2>

After I review the documents, the next level of review requires all the citations to be in endnotes. Is there a way to write a macro that would:


Run through the word document and identify all strings between <***x>
Create a new endnote with the strings as the text of the endnote
Replace the original strings (in the body, including the <> characters) with the numeric superscript assigned when the endnote is created


Result:
George Washington liked apples.1 Thomas Jefferson prefers pears.2

Endnotes
--------------------
[1] Source #1
[1] Source #2

macropod
10-30-2017, 01:26 PM
Try:

Sub Demo()
Application.ScreenUpdating = False
Dim i As Long, RngRf As Range, RngNt As Range
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "\<[!\>]@\>"
.Replacement.Text = ""
.Forward = True
.Format = False
.Wrap = wdFindStop
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
i = i + 1
Set RngNt = .Duplicate
RngNt.Start = RngNt.Start + 1
RngNt.End = RngNt.End - 1
Do While .Characters.First.Previous Like "[ " & Chr(160) & "]"
.Start = .Start - 1
Loop
Set RngRf = .Duplicate
RngRf.Collapse wdCollapseStart
RngRf.Endnotes.Add RngRf
RngRf.End = RngRf.End + 1
RngRf.Endnotes(1).Range.FormattedText = RngNt.FormattedText
.Start = RngRf.End
.Text = vbNullString
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
Set RngNt = Nothing: Set RngRf = Nothing
Application.ScreenUpdating = True
MsgBox i & " references updated."
End Sub

Automate
10-31-2017, 09:23 AM
macropod: This worked perfectly; you are a gentleman and a scholar.

Of course, it just means I have to address my next issue/question, but I'll savor this small victory in the meantime.

Thanks again

Marked as solved.