首页 > 解决方案 > 在 Word 中用尾注文本替换参考

问题描述

我在 Word 中有一个文本,其中包括对尾注的引用 (1,2,3,...)。通过交叉引用创建的同一尾注有多个引用(例如有几个 1)。

我想用尾注文本替换所有引用。

在互联网上,我找到了一个可以做到这一点的代码。问题是,如果有多个对同一个尾注的引用,只有在文档中位置是第一个的引用才会被替换为文本(例如只有第一个 1,其他 1 不会)。

我需要帮助如何用适当的尾注文本替换所有引用。

Sub endnotes2()
  Dim Note As Endnote
  Dim NoteReference As String
  Dim NoteText As String

  For Each Note In ActiveDocument.Endnotes
    With Note
      NoteText = .Range.Text
      NoteReference = .Index
      Call Selection.SetRange(.Reference.End, .Reference.End)
      Selection.Font.Superscript = True
      Selection.TypeText (NoteText)
      Selection.Font.Superscript = False
    End With
  Next Note

  Do While ActiveDocument.Endnotes.Count > 0
    Call ActiveDocument.Endnotes(1).Delete
  Loop

 Selection.Find.ClearFormatting
  Selection.Find.Font.Superscript = True
  Selection.Find.Replacement.ClearFormatting
  Selection.Find.Replacement.Font.Superscript = False
  With Selection.Find
    .Text = ""
    .Replacement.Text = " (^&)" 'The ^& here refers to the "found text", so if we found "abc" we will replace it with "(abc)"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
  End With
  Selection.Find.Execute Replace:=wdReplaceAll
End Sub

标签: vbareferencems-word

解决方案


在我的简单测试中,以下内容对我有用。

由于默认情况下对尾注的交叉引用使用上标,因此搜索上标不是可靠的标准。此外,其他内容也可以上标。交叉引用由 Word 使用Reffields管理,这些引用在使用命令时放置在尾注引用处的书签Insert cross-reference

此类书签以较长的数字开头_Ref。尾注字段使用名称NoteRef。因此,获取尾注引用的书签名称(可能不止一个)是有意义的,检查它们是否使用_Ref模式命名,然后搜索文档以使用书签。

为了“查找”域代码,^d使用了该模式。所以搜索词是那个,后跟字段代码(NoteRef)的名称和书签名称。如果搜索成功,则删除域代码并将尾注文本写入该位置。然后搜索从该点继续到文档的末尾。

所以代码循环遍历所有尾注,获取每个人的引用,获取所有书签,循环书签,检查名称(如上所述)并搜索 NoteRef 字段(如上所述)。

最后,原始尾注引用被尾注文本替换。

Sub WriteEndNoteToAllEndNoteRefs()
    Dim sEndNoteText As String
    Dim rngEndNoteRef As Word.Range, rngSearch As Word.Range
    Dim doc As Word.Document
    Dim en As Word.Endnote
    Dim bkm As Word.Bookmark
    Dim bFound As Boolean

    Set doc = ActiveDocument
    For Each en In doc.Endnotes
        Set rngEndNoteRef = en.Reference
        sEndNoteText = en.Range.Text
        For Each bkm In rngEndNoteRef.Bookmarks
             If Left(bkm.Name, 4) = "_Ref" Then
                Set rngSearch = doc.content
                rngSearch.TextRetrievalMode.IncludeFieldCodes = True
                Do
                    With rngSearch.Find
                        .Text = "^d NoteRef " & bkm.Name
                        .wrap = wdFindStop
                        bFound = .Execute
                        If bFound Then
                            rngSearch.Fields(1).Delete
                            rngSearch.Text = sEndNoteText
                            rngSearch.End = doc.content.End
                        End If
                    End With
                Loop While bFound
             End If
        Next
        rngEndNoteRef = sEndNoteText
    Next

End Sub

推荐阅读