vba - 在 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
解决方案
在我的简单测试中,以下内容对我有用。
由于默认情况下对尾注的交叉引用不使用上标,因此搜索上标不是可靠的标准。此外,其他内容也可以上标。交叉引用由 Word 使用Ref
fields管理,这些引用在使用命令时放置在尾注引用处的书签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
推荐阅读
- antd - 如何在 antdTable 中使用“defaultSortOrder”?
- sql-server - WAS 6.1 的 SQL Server 2016 问题
- path - 如何使用相对路径为 MSTest 的 OpenCover 编写批处理文件,使其变得独立于机器?
- php - 如何在 foreach 循环中创建数组 - php?
- excel - 使用用户窗体调整列表框大小
- sql - 根据年份过滤日期
- neo4j - 将输出作为数组而不是在 neo4j 中的单独行中
- javascript - 将数据数组渲染为分页组件
- node.js - S3 ListObjects 在本地堆栈中不起作用
- mongodb - MongoDB 中 distinct() 的内存高效替代方案