0

I got a great macro for inserting the page number to the beginning of an MS Word endnote here:

Sub InsertPageNumberForEndnotes()
Dim endNoteCount As Integer
Dim curPageNumber As Integer
If ActiveDocument.Endnotes.Count > 0 Then
  For endNoteCount = 1 To ActiveDocument.Endnotes.Count
    Selection.GoTo What:=wdGoToEndnote, Which:=wdGoToAbsolute, _
      Count:=endNoteCount
    curPageNumber = Selection.Information(wdActiveEndPageNumber)
    ActiveDocument.Endnotes(endNoteCount).Range.Select
    ActiveDocument.Application.Selection.Collapse _
      (WdCollapseDirection.wdCollapseStart)
    ActiveDocument.Application.Selection.Paragraphs(1).Range.Characters(3)._
      InsertBefore "Page " & CStr(curPageNumber) & ". "        
  Next
End If    
End Sub

Which processes the endnotes from

^1 Blah blah blah
^2 Blah blah blah 
^3 Blah blah blah

Into

^1 Page 2. Blah blah blah
^2 Page 23. Blah blah blah 
^3 Page 119. Blah blah blah

I now need a second macro to "undo" the changes by removing the "Page nn - " so I can rerun the macro to refresh the page numbers. My thinking is I need to select the first 3 words each end note that begins with "Page", or maybe select the range up to the index of the first "-" character? What change would I need to the above macro to select and delete the text added?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
buttonsrtoys
  • 2,359
  • 3
  • 32
  • 52

1 Answers1

1

This should do the job.

Sub InsertPageNumberForEndnotes()
    ' 04 Oct 2017

    Dim Note As EndNote
    Dim Sp() As String
    Dim n As Long

    For Each Note In ActiveDocument.Endnotes
        With Note.Range
            ' remove "vbTextCompare" to make the search case sensitive
            n = InStr(1, .Text, "page", vbTextCompare)
            If n Then               ' you could make this "If n = 1"
                m = InStr(1, Txt, ". ")
                .Text = Mid(Txt, m + 2)
            End If
        End With
    Next Note
End Sub
buttonsrtoys
  • 2,359
  • 3
  • 32
  • 52
Variatus
  • 14,293
  • 2
  • 14
  • 30
  • 1
    Instead of the inner `For` loop you could capture the text with: `Txt = Split(Mid(Txt, n), " ", 4)(3) – xidgel Oct 03 '17 at 15:41
  • @xidgel Marvellous idea! I incorporated it into my suggested answer forthwith. – Variatus Oct 04 '17 at 02:50
  • @Variatus, thanks! FYI, I tweaked my question and your code a bit to reflect what worked for me – buttonsrtoys Oct 04 '17 at 23:51
  • 1
    You should declare `m` as either Long or Integer. I recommend the use of `Option Explicit` to ensure you can retain control over the variables used in your code. – Variatus Oct 05 '17 at 01:40